简体   繁体   中英

Java lock on static and non static method?

I have the below class and there are few threads wants to access the methods. Please clarify the below points.

If I lock staticMethod method using Object instance lock then any thread owns class lock can access the method simultaneously?

If I lock instanceMethod method using Class instance lock then any thread owns Object lock can access the method simultaneously?

class Test {

          public static synchronized void staticMethod(){
          }

          public synchronized void instanceMethod(){
          }
}

Thanks

Every class loaded in java has corresponding instance of java.lang.Class representing that class, it is that java.lang.Class instance whose lock is used to protect the static methods of the class. Where as instanceMethod uses the object lock.Please see the comments placed over methods below

class Test {
           // lock will be on corresponding instance of **java.lang.Class** 
          //representing Test class
          public static synchronized void staticMethod(){
          }
          // lock will be on corresponding Test Class object
          public synchronized void instanceMethod(){
          }
}

Regarding you ques:
1. If I lock staticMethod method using Object instance lock then any thread owns class lock can access the method simultaneously?
Firstly you should not lock static method with object lock but still if you want to lock it with the object lock then code snippet should be like below and in this case any thread owns class lock can access the method simultaneously only when object lock is not taken by any other thread.

 public static void staticMethod(Test test){
       synchronized(test)
        {               }
      }

2. If I lock instanceMethod method using Class instance lock then any thread owns Object lock can access the method simultaneously? It depends if any thread has put lock over Class instance then thread owns Object lock can't access it otherwise it can.

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