Friday, 23 March 2012

Synchronized block

In java we can add keyword synchronized on the method definition to allow only one thread to execute all object's methods with synchronized at once.
So it looks like this:
  synchronized void add() {
    // some code
  }
It is the same as:
  void add() {
    synchronized(this){
      // some code
    }
  }

When we want to synchronize on the static method we can synchronize on the class object:
  static void add() {
    synchronized(MyClass.class){
      // some code
    }
  }

But it is much more secure to synchronize on the static private object. So only our object can use this lock. On the class object which is public any thread from any piece of code could do it.
So better use this lock:

  private static final Object lock = new Object(); 

  static void add() {
    synchronized(lock){
      // some code
    }
  }

No comments: