javadesign-patternsthread-safetysynchronized-block

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?


Solution

  • 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:

    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() {
       ...
    }