ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

Example of synchronized block in Java

Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then java synchronized block will throw a NullPointerException.

 

public class Singleton{

private static volatile Singleton _instance;

 

public static Singleton getInstance(){

 

   if(_instance == null){

            synchronized(Singleton.class){

              if(_instance == null)

              _instance = new Singleton();

            }

 

   }

   return _instance;

 

}

 

This is a classic example of double checked locking in Singleton. In this example of java synchronized code we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance because if you make whole method synchronized every call of this method will be blocked while you only need to create instance on first call. To read more about Singleton in Java see here.

 

When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.

Related Posts Plugin for WordPress, Blogger...
Flag Counter