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

ぃ、小莉子 提交于 2019-12-24 17:09:17

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/25642642/static-synchronized-method-provides-class-level-lock-what-does-class-level-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!