Saturday, 23 April 2016

How to achieve Atomicity in multithreaded programs ?


Operations A and B are atomic in case thread executing A and another thread executes B, either all of B has executed or none of it has.


Making the state atomic
Use atomic variables from package java.util.concurrent.atomic which ensure that all actions that access the state are atomic.

Example
public class Test {
   private final AtomicLong count = new AtomicLong(0);
   public long getCount() { 
      return count.get()
   }
   public void service(int i) {
      //-------
      count.incrementAndGet();
 
      //-------   
   }
}

By replacing long value with AtomicLong, we can ensure that all actions that access the count state are atomic.

As state of class is count, and count is made thread-safe , so class (as a whole) became thread-safe.


Classes in java.util.concurrent.atomic package :
  • AtomicBoolean    
  • AtomicInteger    
  • AtomicIntegerArray    
  • AtomicLong    
  • AtomicLongArray    
  • AtomicReference<V>    
  • AtomicReferenceArray<E>    
and many more.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.