Is something like this possible with synchronized
, or do I need to use java.util...Lock
:
public void outer() {
synchronized(lock) {
inner();
}
}
public void inner() {
thing1();
release(lock) {
result = doLongNetworkRequest();
}
thing2(result);
}
Thread inside the synchronized method is set as the owner of the lock and is in RUNNABLE state. Any thread that attempts to enter the locked method becomes BLOCKED. When thread calls wait it releases the current object lock (it keeps all locks from other objects) and than goes to WAITING state.
The lock can be released as soon as the block it protects is finished which means after the return but before the finalized block. That does not mean that the jvm is not allowed to keep the lock a bit longer if it thinks it will improve performance. When one thread reaches the finally block, it has released the lock.
"Calling notify() method on an object releases the lock of that object." and later "But when a thread calls notify() method on an object, the thread may not release the lock of that object immediately" in this answer contradict each other.
The newCondition() method The lock must be held by the current thread before waiting on the condition. A call to the condition. wait() will atomically release the lock before the wait and re-acquire the lock before the wait returns.
You can use the java.util.concurrent.locks
. They have lock()
and unlock()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With