Concurrency sparked widespread interest in functional programming. Multithreaded programming, requiring synchronized access to shared, mutable state, is the assembly language of concurrency.
- Immutable values make synchronization unnecessary.
- i. Actors
- ii. Software Transactional Memory.
The Actor
Model
In the
Actor model of concurrency, work is coordinated by message passing between
“actors.” Each actor has a queue, sometimes called a mailbox, for incoming
messages. The actor processes each message, one at
a time. Perhaps the best known implementation of actors is found in Erlang,
where actors are the
core of everything you do in the language.- case class Greeting(who: String)
- class GreetingActor extends Actor with ActorLogging {
- def receive = {
- case Greeting(who) ⇒ log.info("Hello " + who)
- }
- }
- val system = ActorSystem("MySystem")
- val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
- greeter ! Greeting("Charlie Parker")
Software Transactional Memory
Most of us have worked on “RDBMS”. They support ACID transactions. The goal of ACID transactions is to avoid logical inconsistencies in a given set of related records. Software Transactional Memory (STM) brings transactions to locations in memory that are referenced by variables). STM can’t provide durability, because memory isn’t durable (e.g., if the power is lost), but STM can provide
the ACI, atomicity, consistency, and isolation in ACID.
Figure below shows the state at time “0.” There are two references pointing the same value1 of a persistent data structure.
Now let’s change ref2 to point to a new, updated value, as shown below:
By time “1,” an STM transaction in the context of ref2 has been used to move its reference to value2, which was created from value1, as indicated by the dotted line. Creating value2 does not necessary have to occur within the transaction, just the reassignment of ref2. This behavior allows different clients to acquire references to the same value at a particular time, but each can work with the value without fear that it will change unexpectedly, due to the actions of one of the other clients. A version with no references will be garbage collected.
There are several STM libraries for Java, many of which are inspired by Clojure’s implementation. Akka integrates with the Multiverse STM.
The main intent of these concepts is to provide new and higher level of abstraction to developers. This will enable them to write better concurrent programs.
Add a comment