What does intrinsic lock actually mean for a Java class?

前端 未结 7 1526
逝去的感伤
逝去的感伤 2021-02-04 10:50

In order to properly understand the issues and solutions for concurrency in Java, I was going through the official Java tutorial. In one of the pages they defined Intrin

7条回答
  •  别跟我提以往
    2021-02-04 11:31

    Seems you have one misunderstanding (dunno if it caused the wrong conclusion) that no one has pointed out. Anyway, a brief answer:

    Intrinsic Lock: Just think it as, every object in JVM has internally a lock. synchronized keywords tries to acquire the lock of the target object. Whenever you synchronized (a) { doSomething; }, what actually happens is

    1. the lock in a is acquired
    2. code within the synchronized block is run (doSomething)
    3. release the lock in a

    and I wish you know

    public synchronized void foo() {
      doSomething;
    }
    

    is conceptually the same as

    public void foo() {
        synchronized(this) {
            doSomething;
        }
    }
    

    Ok, go back to your question, the biggest problem, imho, is :

    For me this means that once I call a synchronized method from one of the threads, I will have hold of the intrinsic lock of the thread and since...

    It is wrong. When you call a synchronized method, you are not get hold of the lock of the thread.

    Instead, that thread will own the intrinsic lock of the object that is "owning" the method.

    e.g. in thread1, you called a.foo(), and assume foo() is synchronized. thread1 is going to acquire the intrinsic lock of the object a referring.

    Similarly, if AClass.bar() is called (and bar is synchronized and a static method), the intrinsic lock of AClass Class object will be acquired.

提交回复
热议问题