Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're creating a new Lock object with every invocation of the method so each thread locks on a different object.</p> <p>Take out this line </p> <pre><code>final Lock lock = new ReentrantLock(); </code></pre> <p>Outside the method making it a class member and it should work correctly.</p> <p>@Edit: ok more in-depth explanation:</p> <p>Making a method synchronized protects it with a lock on an object just like you'd do it with a Lock object yourself. If it's a non static method the lock is done on "this" object. Since you have a static method here the lock will be on the object representing your Guys class. There is one such object so there will be only one lock to be obtained. If one thread holds the lock others have to wait.</p> <p>What you are doing here is creating a new Lock object on every invocation of go() method therefore each thread calling the go() method acquires a different lock which defends you from nothing because only that thread can call lock.lock() on it (as I said other threads will invoke lock() on their own instances of Lock).</p> <p>Taking this Lock variable out of the method and making it a class variable will mean that all the threads invoking the go() method will try to acquire the same lock - similar to what synchronized does.</p> <p>@Edit2: to show it more vividly it is like when there is a group of people and only the person holding a stick can speak. All is ok when there is only 1 stick (which is the case with synchronized method or a shared Lock object). But obviously when it is a group of Polish people (editorial note I am Polish so I can make fun of my own people) everyone will bring their own stick with them (and it is similar with your new ReentrantLock() here). This will result in everyone speaking at the same time. And obviously everyone will be like "omg but I have a stick, I have the full right to speak now!".</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