How to detect deadlock ? Timeout in synchronized block?
deadlock, java, multithreading
Solution
You can use a java.util.concurrent.Lock instead of the intrinsic `Object` locks. RentrantLock without fair ordering has the same basic behaviour and semantics as an intrinsic lock. There is a method `tryLock` that takes a timeout parameter:
Lock lock = ...;
if (lock.tryLock(10L, TimeUnit.SECONDS)) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
Problem
I’m debugging a Java application that runs several threads. After a while of watching the log it seems that one of those threads is not running anymore. My guess is that the thread is waiting for a lock that is never released (the last output is before calling a synchronized method). Can I configure a timeout to the thread; a sort of “wait for this lock but if it not available after 10 seconds don’t wait anymore!”