What does intrinsic lock actually mean for a Java class?

前端 未结 7 1616
逝去的感伤
逝去的感伤 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条回答
  •  Happy的楠姐
    2021-02-04 11:04

    would I be unable to call another synchronized method of the same class? If yes, then the whole purpose of having synchronized methods is defeated. Isn't it?

    No. You can't call other synchronized method on same object for Object level lock and you can't call other static sysnchronized method on same class.

    But it does not defeat the purpose of having synchronisation.

    If you follow the other documentation page on synchronized methods:

    Making these methods synchronized has two effects:

    1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    2. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

    If you allow two synchronized method to run in parallel. you will bound to get memory inconsistency errors on shared data.

    On a different note, Lock provides better alternative synchronized construct.

    Related SE question:

    Synchronization vs Lock

提交回复
热议问题