如何检测死锁?同步块超时? [英] How to detect deadlock ? Timeout in synchronized block?
问题描述
我正在调试运行多个线程的Java应用程序.在查看日志一段时间后,似乎这些线程之一不再运行.我的猜测是线程正在等待永远不会释放的锁(最后的输出是在调用同步方法之前).
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).
我可以配置线程超时吗?一种等待此锁,但如果10秒钟后仍不可用,就不要再等待!"
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!"
推荐答案
您可以使用 RentrantLock 没有合理的顺序与内在锁相同的基本行为和语义.有一种方法 tryLock
需要一个超时参数:
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
}
这篇关于如何检测死锁?同步块超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!