質問

As per my understanding synchronize on non-static method will blocked at object level and synchronize on static method will be blocked at class instance level.

Based on that please find below my understanding on various scenarios:

  1. non-static synchronize method access then other non-static synchronize method also block

  2. non-static synchronize method access then non-static non-synchronize method doesn't block.

  3. static synchrnize method access then other synchronize (static & non-static) methods for that class instance blocked.

  4. static synchronize method access then other non-static non-synchronize method doesn't block.

  5. static synchronize method access then other static non-synchronize method doesn't block.

  6. static synchronize method access then non-static synchronize method blocked for all the object instance.

  7. non-static synchrnize method access then static synchronize method doesn't block

Please help me to verify the same.

役に立ちましたか?

解決

I think it can be explained simpler

1) when a thread has entered a synchronized instance method then no other thread can enter any of synchronized instance methods of the same instance

2) when a thread entered a synchronized static method then no other thread can enter any of synchronized static methods of the same class

他のヒント

A static synchronized method just locks the instance of Class which represents that class. Locking the class doesn't block any other methods e.g. non-static ones.

e.g.

class MyClass {
    public static synchronized void method() {
        // something 
    }

is equivalent to

class MyClass {
    public static void method() {
        synchronized(MyClass.class) {
            // something 
        }
    }

There are two type of locks: Object Level and Class Level.

Object Level lock is applicable on the non-static synchronized methods. Every object has a lock while using the method, the object first acquires the lock, then the code inside the method is executed.

Class Level locks are applicable on the static synchronized methods. Every class has a lock which is used when calling the synchronized static method.

Here are the answers to your questions:

  1. false

  2. true

  3. non-static synchronized method cannot be accessed by the static synchronized method. But non-static synchronized method can access the static synchronized method. If we access the static synchronized method then all the static synchronized methods get blocked but we can access the other static and non-static methods.

  4. static synchronized method access does not block other non-static, non-synchronized methods.

  5. static non-synchronized methods will be accessible.

  6. non-static synchronized methods will be blocked as explained above.

  7. Object level lock can contain the class level lock which means a non-static synchronized method can call the static synchronized methods.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top