Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How class level lock is acquired

public synchronized int getCountOne() {
        return count++;
 }

Like in above code synchronizing on the method is functionally equivalent to having a synchronized (this) block around the body of the method. The object "this" doesn't become locked, rather the object "this" is used as the mutex and the body is prevented from executing concurrently with other code sections also synchronized on "this."

On similar grounds what is used as a mutex when we acquire a class level lock.As in if we have a function

public static synchronized int getCountTwo() {
        return count++;
 }

obviously two threads can simultaneously obtain locks on getCountOne(object level lock) and getCountTwo(class level lock). So as getCountOne is analogous to

public int getCountOne() {
     synchronized(this) {
          return count++;
     }
 }

is there an equivalent of getCountTwo? If no what criteria is used to obtain a Class level lock?

like image 906
Aniket Thakur Avatar asked Jul 22 '13 09:07

Aniket Thakur


1 Answers

On similar grounds what is used as a mutex when we acquire a class level lock

The class object itself will be used as mutex. The equivalent synchronized block for your static synchronized method will look like:

public static int getCountTwo() {
     synchronized(ClassName.class) {
          return count++;
     }
}

ClassName is the name of the class containing that method.

See JLS Section §8.4.3.6:

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

Emphasis mine.

like image 152
Rohit Jain Avatar answered Sep 18 '22 07:09

Rohit Jain