Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner synchronization on the same object as the outer synchronization

Recently I attended a lecture concerning some design patterns:

The following code had been displayed:

public static Singleton getInstance()
{
  if (instance == null)
  {
    synchronized(Singleton.class) {      //1
      Singleton inst = instance;         //2
      if (inst == null)
      {
        synchronized(Singleton.class) {  //3
          inst = new Singleton();        //4
        }
        instance = inst;                 //5
      }
    }
  }
  return instance;
}

taken from: Double-checked locking: Take two

My question has nothing to do with the above mentioned pattern but with the synchronized blocks:

Is there any benefit whatsoever to the double synchronization done in lines 1 & 3 with regards to the fact that the synchronize operation is done on the same Object?

like image 605
Yaneeve Avatar asked Mar 17 '10 15:03

Yaneeve


People also ask

Do synchronized methods synchronize on the object or the class?

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.

How does synchronized work internally?

When we use a synchronized block, Java internally uses a monitor, also known as monitor lock or intrinsic lock, to provide synchronization. These monitors are bound to an object; therefore, all synchronized blocks of the same object can have only one thread executing them at the same time.

What is the difference between a synchronized method and a synchronized block?

Key DifferencesA synchronized method assigns an object-level or class-level corresponding lock. And synchronized block assign a lock to the object based on the parameter.

What happens when synchronized object is invoked?

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.


1 Answers

In the old Java Memory Model (JMM), exiting a synchronized block allegedly flushed local data out to main memory. Entering a synchronized block used to cause rereading of cached data. (Here, cache includes registers with associated compiler optimisations.) The old JMM was broken and not implemented correctly.

In the new JMM it doesn't do anything. New JMM is specified for 1.5, and implemented for the "Sun" 1.4 JRE. 1.5 completed it's End of Service Life period some time ago, so you shouldn't need to worry about the old JMM (well, perhaps Java ME will do something unpredictable).

like image 65
Tom Hawtin - tackline Avatar answered Oct 22 '22 14:10

Tom Hawtin - tackline