Sunday, 9 June 2013

Interview Question #13 synchronization on static function/method.

Let me clarify the question with an example. You have the following class.

public class Counter{
private static int count = 0;

public static synchronized int getCount()
  return count;

public synchronized setCount(int count)
   this.count = count;


You have multi threaded environment. Can two threads simultaneously access
or process getCount() and setCount() methods? 
Even if we have following case.

Counter myCounter = new Counter();


First of all you should not access static functions/block using class instance. Though it is perfectly valid to do so. Why is it valid? Each of the class instances(objects) have class information and hence can hence access it. Lets get to our original question on synchronization.

Answer is yes! Two threads can simultaneously operate/process on the two functions getCount() and setCount(). This is because when synchronized method setCount() is called thread acquires an object level lock where as when getCount() method is called it being a static method(owned by class rather than it's instances) acquires a class level lock.

When you use synchronized method or a block lock is obtained on the monitor if the corresponding instance. So in above example for setCount() method lock obtained will be on the myCounter instance where as for method getCount() which is a static or class method lock is obtained on the Class object. You can get this object by using .class keyword or getClass() method. This Class object will be same for all the instances of that class.
t> UA-39527780-1 back to top