STM in Clojure and Actors

Learn about STM and actors in the Akka framework.

We'll cover the following

STM in Clojure

STM results in a separation of State and Identity. For example, the stock price at a given time is immutable. We must use a Transaction to modify anything. We can include the Clojure jars and use them within Java. For example, in the following code, referenceToAmount can only be modified inside of a Transaction:

import Clojure.lang.*
Ref referenceToAmount;
LockingTransaction.runInTransaction(new Callable() {
        referenceToAmount.set(value);
});

We will get an error if we try to modify the Ref outside of a Transaction. This makes concurrent programming easier because modifying data outside of a synchronize block is impossible.

Actors

The Scala-based actor framework, Akka, can also be used from Java.

The following code shows a simple example using the Akka framework with one actor:

import akka.actor.*
public class XActor extends UntypedActor {
     public void onReceive(Object message) throws Exception {
          if (message instanceof String)
             System.out.println((String) message);
     }
}
public static void main(String... args) {
         ActorSystem system = ActorSystem.create("MySystem");
         ActorRef actor = system.actorOf(new Props(XActor.class), "actor");
         // the message could be anything implementing Serializable
         actor.tell("Message String");
}

An actor runs in a dedicated thread, so it can only do one thing at a time. This makes concurrency much easier to implement.

Get hands-on with 1200+ tech skills courses.