Tuesday, September 3, 2013

Thread interference and Memory consistency errors.

Generally threads communicates by sharing member variables and the Object references members refer to. Well this type of communication is extremely efficient but can cause two kind of problems :

1. Thread Interference 
2. Memory Consistency Errors 

Interference occurs when two operations , running in different threads , but acting on the same data , interleave.

See the Counter class  ( example taken from docs.oracle.com ).

class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}
Suppose there are two threads Thread-A and Thread-B working on the same counter instance  . Say Thread-A invokes increment() , and at the same time Thread-B invokes decrement() . Thread-A reads the value c and  increment it by 1 . At the same time Thread-B reads the value ( which is 0 because the incremented value is not yet set by Thread-A) , decrements it and set it to -1 . Now Thread-A sets the value to 1 .

Oops what went wrong ? The result of Thread-B is lost. It might be the other case as well or there could be no error at all . This uncertainty makes it difficult to identify bugs .

Memory Consistency Errors occurs when different threads have inconsistent views of the shared data. 

In the above class counter , Lets say there are two threads working on the same counter instance ,  calls the increment method to increase the counter's value by 1 . Here it is no guarantee that the changes made by one thread is visible to the other .

Avoiding Memory Consistency Errors
This can be avoided by establishing a happens-before relationship . This relationship guarantees that memory write by one thread is visible to a read by other thread if the write operation happens-before the read operation. There are various actions that can form a happens-before relationship.

  • Synchronization
  • volatile keyword
  • Thread.start()
  • Thread.join()


No comments :

Post a Comment