Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>That is the whole concept of synchronization, if you are taking a lock on an object (or a class), none of the other threads can access any synchronized blocks.</p> <p>Example </p> <pre><code>Class A{ public void method1() { synchronized(this)//Block 1 taking lock on Object { //do something } } public void method2() { synchronized(this)//Block 2 taking lock on Object { //do something } } } </code></pre> <p>If one thread of an Object enters any of the synchronized blocks, all others threads <strong>of the same object</strong> will have to wait for that thread to come out of the synchronized block to enter any of the synchronized blocks. If there are N number of such blocks, only one thread of the Object can access only one block at a time. Please note my emphasis on <strong>Threads of same Object</strong>. The concept will not apply if we are dealing with threads from different objects. </p> <p>Let me also add that if you are taking a lock on <strong>class</strong>, the above concept will get expanded to any object of the class. So if instead of saying <code>synchronized(this)</code>, I would have used <code>synchronized(A.class)</code>, code will instruct JVM, that irrespective of the Object that thread belongs to, make it wait for other thread to finish the synchronized block execution.</p> <p>Edit: Please understand that when you are taking a lock (by using synchronized keyword), you are not just taking lock on one block. You are taking lock on the object. That means you are telling JVM "hey, this thread is doing some <strong>critical work</strong> which might change the state of the object (or class), so don't let any other thread do any other <strong>critical work</strong>" . Critical work, here refers to all the code in synchronized blocks which take lock on that particular Object (or class), and not only in one synchronized block. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload