From the above code the output is a below
Held by me: false
Lock acquired: true
came in here
But from the above code,i am obtaining the lock in second executor task without unlocking the lock in first executor task(which is commented).My question is how can the output "Lock acquiredaaaa===" is true,since the lock cannot be obtained when it is still in locked state in another task. Can any one please help me on this.
If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.
In any case, even if that wasn't happening, you have a thread pool with a single thread in it, so the second thread won't execute until the first one has finished.
There is also something odd here; you appear to be locking the lock twice and only unlocking it once. There is nothing to stop you doing that; if you put the entire code in a loop and go on long enough, you will find out what is happening.
The whole idea of a reentrant lock (by the way: Lock isn't a class but an interface) is to permit recursive locking.Let's imagine that thread 1 accessed the bar method. So the lock is locked once. Then, which thread is allowed to access any of the methods with the same Lock instance attached, foo, baz, bizz, bozz and buzz? Answer: the same thread. No other thread can access any method with the same Lock instance associated with it until thread 1 has finished completely; that will generate a sort of happens‑before relationship between whatever this thread does and whatever follows it. As DT says, you only have one thread at all, so that thread is permitted access to any code with that same lock on.
Campbell Ritchie wrote:Will it even be a second thread? . . . As DT says, you only have one thread at all, so that thread is permitted access to any code with that same lock on.
That was a very good explanation got my doubt clarified.
That's a pleasure
srikanth darbha wrote:. . . Thanks, Ritche, . . . .
Please don't quote the whole of old posts, which simply makes the thread longer and longer. I have removed most of it, not noticing that it had been referred back to you.