Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Timeout to avoid deadlock in Java multithreading

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 ?

like image 516
Kaushik Lele Avatar asked Dec 06 '12 10:12

Kaushik Lele


1 Answers

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.

like image 193
Stuart Cardall Avatar answered Oct 10 '22 20:10

Stuart Cardall