Saturday, April 6, 2013

What if we don't synchronize the getters/accessors of a shared mutable object in multi-threaded applications ?


From Effective Java 2nd Edition - Item 66

When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization. In fact, synchronization has no effect unless both read and write operations are synchronized.

Synchronization serves two major purposes in a multi-threaded scenario, one is atomicity of the operation and second is the memory visibility of the changes made by one thread to all other threads (Brian Goetz article on read and write barriers). In case of getters the changes made to the shared variable will get reflected to the new thread if the code block is synchronized, otherwise dirty reads may happen and the thread may see the stale state of the shared object.

So all the methods returning the mutable protected state of the shared object must be synchronized unless the  field returned is immutable, final or volatile.

Let's take example of a simple Counter Class.

public class Counter {
 private int c = 0;
 public synchronized void increment() {
  c++;
 }

 public synchronized int getValue() {  /*Must be synchronized to see the guaranteed correct value*/
  return c;
 }
}
That's the reason that get() method of vector class is synchronized & must be synchronized.

No comments:

Post a Comment

Your comment will be published after review from moderator