Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing a "synchronized" lock

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);
}
like image 782
Bart van Heukelom Avatar asked May 04 '11 08:05

Bart van Heukelom


People also ask

How do you release a lock on a synchronized block?

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.

When leaving a synchronized block one has to make sure the lock is released by always using a try finally construct?

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.

Which method is used to release the lock held by an object?

"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.

Which method releases the lock in thread?

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.


1 Answers

You can use the java.util.concurrent.locks. They have lock() and unlock()

like image 199
Bozho Avatar answered Sep 28 '22 11:09

Bozho