Rajan
Rajan

Reputation: 125

Why do we write Synchronized(ClassName.class)

I have a question in singleton pattern. In singleton pattern we write

synchronized(ClassName.class){

     // other code goes here

}

What is the purpose of writing ClassName.class?

Upvotes: 2

Views: 4428

Answers (3)

BrianT.
BrianT.

Reputation: 404

In a member method (non-static) you have two choices of which monitor (lock) to use: "this" and "my class's single static lock".

If your purpose is to coordinate a lock on the object instance, use "this":

...
synchronized (this) {
  // do critical code
}

or

public synchronized void doSomething() {
 ...
}

However, if you are trying to have safe operations including either:

  • static methods

  • static members of your class

Then it is critical to grab a class-wide-lock. There are 2 ways to synchronize on the static lock:

...
synchornized(ClassName.class) {
   // do class wide critical code
}

or

public static synchronized void doSomeStaticThing() {
   ...
}

VERY IMPORTANTLY, the following 2 methods DO NOT coordinate on the same lock:

public synchronized void doMemberSomething() {
   ...
}

and

public static synchronized void doStaticSomething() {
   ...
}

Upvotes: 4

StuPointerException
StuPointerException

Reputation: 7267

The object that you pass into the synchronized block is known as a monitor. Since the object that represents the class className.class is guaranteed to only exist once in the JVM it means that only one thread can enter that synchronized block.

It is used within the singleton pattern to ensure that a single instance exists in the JVM.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691765

Each class (for example Foo) has a corresponding, unique instance of java.lang.Class<Foo>. Foo.class is a literal of type Class<Foo> that allows getting a reference to this unique instance. And using

synchronized(Foo.class) 

allows synchronizing on this object.

Upvotes: 1

Related Questions