Sunday, September 28, 2014

Synchronization


At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time.
The process by which this is achieved is called synchronization

Why use Synchronization

    To prevent thread interference.

    To prevent consistency problem.




Suppose we have two different threads T1 and T2, T1 starts execution and save certain values in a file temporary.txt which will be used to calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will return wrong result.

To prevent such problems, synchronization was introduced. With synchronization in above case, once T1 starts using temporary.txt file, this file will be locked (LOCK mode), and no other thread will be able to access or modify it until T1 returns.

Sample method
 public class Counter {
  private int count = 0;
  public synchronized void increment() {
      count++;
  }
  public synchronized int getCount() {
      return count;
  }
}

  •  If you declare any method as synchronized, it is known as synchronized method.
  • Synchronized method is used to lock an object for any shared resource.
  • When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes.

No comments:

Post a Comment