Why do we write Synchronized(ClassName.class)

2019-08-12 16:18发布

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?

3条回答
我命由我不由天
2楼-- · 2019-08-12 16:51

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.

查看更多
甜甜的少女心
3楼-- · 2019-08-12 17:00

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.

查看更多
▲ chillily
4楼-- · 2019-08-12 17:03

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() {
   ...
}
查看更多
登录 后发表回答