One of the strategy to avoid deadlock situation in Java Multithreading is using timeout. Suppose, one thread has acquired lock on one resource and now waiting for lock on another resource. After certain time period if it can not acquire lock on resource2 then it should stop waiting for lock on resource2. Also it should release lock on resource1. Thus deadlocks will be avoided.
But how to implement it in Java ? How to explicitly "release" lock ? How to define timeout to wait for lock.
What is exact java commands and syntax. Any hello-worldish example please ?
In the Java 8+ Concurrency API you can set an explicit time for a lock
to wait when it's condition is set:
private Lock lock = new ReentrantLock();
private Condition myCondition = lock.newCondition();
try{
myCondition.await(1200L, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
System.out.println((e);
} finally{
lock.unlock();
}
The lock will wait until it receives a signal()
or signalAll()
from another thread or until the time of 1.2 seconds expires.
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