Showing posts with label STM. Show all posts
Showing posts with label STM. Show all posts

Wednesday, January 2, 2013

Software Transactional Memory (STM)

The Actor Model is based on the premise of small independent processes working in isolation and where the state can be updated only via message passing. The actors hold the state within themselves, but the asynchronous message passing means there is no guarantee that a stable view of the state can be provided to the calling components. For transactional systems like banking where account deposit and withdrawal need to be atomic, this is a bad fit with an Actor Model.So, if your Akka applications need to be implementing a shared state model and providing a consensual, stable view of the state across the calling components, Software Transactional Memory (STM) provides the answer.

STM provides a concurrency-control mechanism for managing access to shared memory. STM makes use of two concepts –  optimism and transactions to manage the shared concurrency control.
  • Optimism means that we run multiple atomic blocks in parallel, assuming there will be no errors. When we are done, we check for any problems. If no problems are found, we update the state variables in the atomic block. If we find problems then we roll back and retry. Optimistic concurrency typically provides better scalability options than any other alternate approaches. 
  • Secondly, STM is modeled on similar lines of database transaction handling. In the case of STM, the Java heap is the transactional data set with begin/commit and rollback constructs. As the objects hold the state in  memory, the transaction only implements the following characteristics – atomicity, consistency, and isolation.

Tuesday, May 22, 2012

Playing PingPong with STM - Refs and Agents

PingPong is a classic example where 2 players (or threads) access a shared resource - PingPong Table and pass the Ball (state variable) between each other. With any shared resource, unless we synchronize the access, the threads can run into potential deadlock situation.

The PingPong algorithm is very simple

if my turn {
     update whose turn is next
     ping/pong - log the hit
     notify other threads
} else {
    wait for notification
}



Let's take an example and see how this works! Here is our Player class, which implements Runnable and takes in the access to the shared resource and a message