?????????????????????????????????????????????????ж???????????????????????????????μ??????????????????????????????????????????????????????????????????????????????????У????????????з???????????????????????????????????????????п??????????????????????????Щ???????????????????????????????????????????б??????????????????????????????????????????????????????????????????Щ?????????顣
??????????????ThreadMXBean???????????
????Java 5??????ThreadMXBean?????????????????????????????????????????Щ??????????????????????????????????????????????????????????????????????????????????findMonitorDeadlockedThreads?????????????Java 6????????????findDeadlockedThreads???????????????findDeadlockedThreads????????owner locks??java.util.concurrent???????????????findMonitorDeadlockedThreads?????monitor locks?????磬????飩???????????汾????????????????????????????????°汾????????????????????????????????????????????????????????????????????????????????
???????????????????????????????????????ó?????????????????
????ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
????this.scheduler.scheduleAtFixedRate(deadlockCheck?? period?? period?? unit);
?????????????????????????????????λ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????ж???
????void handleDeadlock(final ThreadInfo[] deadlockedThreads);
????????????????????????????????
public interface DeadlockHandler {
void handleDeadlock(final ThreadInfo[] deadlockedThreads);
}
public class DeadlockDetector {
private final DeadlockHandler deadlockHandler;
private final long period;
private final TimeUnit unit;
private final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final Runnable deadlockCheck = new Runnable() {
@Override
public void run() {
long[] deadlockedThreadIds = DeadlockDetector.this.mbean.findDeadlockedThreads();
if (deadlockedThreadIds != null) {
ThreadInfo[] threadInfos =
DeadlockDetector.this.mbean.getThreadInfo(deadlockedThreadIds);
DeadlockDetector.this.deadlockHandler.handleDeadlock(threadInfos);
}
}
};
public DeadlockDetector(final DeadlockHandler deadlockHandler??
final long period?? final TimeUnit unit) {
this.deadlockHandler = deadlockHandler;
this.period = period;
this.unit = unit;
}
public void start() {
this.scheduler.scheduleAtFixedRate(
this.deadlockCheck?? this.period?? this.period?? this.unit);
}
}