How to detect deadlock ? Timeout in synchronized block?

后端 未结 7 2080
北荒
北荒 2020-12-29 09:00

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

7条回答
  •  情话喂你
    2020-12-29 09:35

    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
    }
    

提交回复
热议问题