简体   繁体   中英

Static Synchronized method provides Class level lock. What does Class Level Lock means?

Does it mean that any Thread irrespective of the object it obtain will not interfere other Thread executing in Synchronized static method. Even if we call with class_name.static_Method.

Ex- If we have two thread :

public class Test implements Runnable {

  public synchronized static testMethod(){}

  public void run(){ testMethod(); }

  public static void main(String[] args) {
   Test obj1=new Test();
   Test obj2=new Test();
   Thread t1=new Thread(obj1);
   Thread t2=new Thread(obj2);
   t1.start(); // thread on object obj1
   t2.start(); // Thread on object obj2
   Test.testMethod(); // main thread
}
}

If Thread t1 enters static method then t2 and main thread will not enter the method even though both have different object. Correct me If I am wrong.

You're thinking about this all wrong. Don't write this:

public class Test implements Runnable {
    static synchronized SomeType testMethod() { ... }
    ...
}

Write this instead. It means exactly the same thing, but it reveals what's going on:

public class Test implements Runnable {
    static SomeType testMethod() { synchronized(Test.class) {...} }
    ...
}

Then, all you need to know is that Test.class is a unique object (it's the object that holds the description of your Test class), and of course, no two threads can ever synchronize on the same object at the same time.

Same thing goes for synchronized instance methods: This,

public class Test implements Runnable {
    synchronized SomeType testMethod() { ... }
    ...
}

Means the same thing as

public class Test implements Runnable {
    SomeType testMethod() { synchronized(this) {...} }
    ...
}

But the second one shows you what's really going on.

If Thread t1 enters static method then t2 and main thread will not enter the method even though both have different object

its a static method, which is a class level (common) method to all the instances (objects) of that class, hence, objects doesn't matter. If its declared as synchronized , then the Thread which will execute the method will acquire the lock on the class object ( Class<Test> object)

a static synchronized method can be thought of like below

public static testMethod(){
   synchronized(Test.class) {
      //method body
   }
}

Since a class gets loaded once (unless you define your custom class-loader and re-load the class), there will be only one class object, which acts as lock for mutual exclusion

T1 and T2 are synchronizing on Object Test.class . Remember classes are Objects of type java.lang.Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM