Sunday, September 2, 2012

Threading in core Java

==========
Synchronized block vs Synchronized method?


When to use Synchronized block and when synchronized method?

If method has only few lines to by synchronized which way will you prefer for synchronization?
========

if you go for synchronized block it will lock a specific object. 
if you go for synchronized method it will lock all the objects. 

If there is a separate class and has one method. You want to call that method with restricted access then use synchronized block. Else use synchronized method.

Synchronized methods are used when we are sure all instance will work on the same set of data through the same function
Synchronized block is used when we use code which we cannot modify ourselves like third party jars etc


The object taken in the parantheses by the synchronized construct is called a monitor object.

public class Counter{
     
     long count = 0;
    
     public synchronized void add(long value){
       this.count += value;
     }
  }
  public class CounterThread extends Thread{
 
     protected Counter counter = null;
 
     public CounterThread(Counter counter){
        this.counter = counter;
     }
 
     public void run() {
            for(int i=0; i<10; i++){
           counter.add(i);
        }
     }
  }
  public class Example {
 
    public static void main(String[] args){
      Counter counter = new Counter();
      Thread  threadA = new CounterThread(counter);
      Thread  threadB = new CounterThread(counter);
 
      threadA.start();
      threadB.start(); 
    }
  }
Two threads thread are created. The same Counter instance is passed to both of them in their constructor. The Counter.add() method is synchronized on the instance, because the add method is an instance method, and marked as synchronized. Therefore only one of the threads can call the add() method at a time. The other thread will wait until the first thread leaves the add() method, before it can execute the method itself.
If the two threads had referenced two separate Counter instances, there would have been no problems calling the add() methods simultanously. The calls would have been to different objects, so the methods called would also be synchronized on different objects (the object owning the method). Therefore the calls would not block. Here is how that could look:
  public class Example {
 
    public static void main(String[] args){
      Counter counterA = new Counter();
      Counter counterB = new Counter();
      Thread  threadA = new CounterThread(counterA);
      Thread  threadB = new CounterThread(counterB);
 
      threadA.start();
      threadB.start(); 
    }
  }
Notice how the two threads, threadA and threadB, no longer reference the same counter instance.




No comments:

Post a Comment