我正在尝试寻找一种更好的方法来对死锁问题进行三角测量。
一种方法可能是是否存在强制转储/data/anr/traces.txt的方法。我还没有找到使用更新的android版本做到这一点的方法,但是,我更愿意在我的应用程序中处理它。
状态可以轻松获得线程列表。当线程被阻塞时,调用堆栈通常可以很好地说明哪些对象可能已被锁定从而阻塞了线程。
但是,哪些其他对象已被特定线程锁定并不总是那么明显。我希望能够列出被阻塞的线程以及被其阻塞的对象,但是我想列出具有被锁定对象的线程。
有没有办法列出被线程锁定(同步)的对象?
编辑: 我想通过在ui线程中永远等待来故意导致anr会导致转储anr痕迹...
private void onDeadlock() {
Map<Thread,StackTraceElement[]> stackTraceMap = Thread.getallStackTraces();
List<Thread> threads = new ArrayList<>(stackTraceMap.keySet());
List<Thread> blocked = extractByState(threads,State.BLOCKED);
List<Thread> runnable = extractByState(threads,State.RUNNABLE);
// List Threads that are blocked
for (Thread thread : blocked) {
String callStack = asString(stackTraceMap.get(thread));
// How to find object which is blocking execution?
Object blocking = "";
// How to find objects that this thread has locked (synchronized)?
Object[] lockedByThread = new Object[0];
LOG.d("onDeadlock Thread = {} State = {} blocked by {} locking {} stack {}",thread.getName(),thread.getState(),blocking,Arrays.toString(lockedByThread),callStack);
}
// List Threads that are running
for (Thread thread : runnable) {
String callStack = asString(stackTraceMap.get(thread));
// How to find objects that this thread has locked (synchronized)?
Object[] lockedByThread = new Object[0];
LOG.d("onDeadlock Thread = {} State = {} locking {} stack {}",callStack);
}
// List remaining threads
for (Thread thread : threads) {
String callStack = asString(stackTraceMap.get(thread));
// How to find objects that this thread has locked (synchronized)?
Object[] lockedByThread = new Object[0];
LOG.d("onDeadlock Thread = {} State = {} locking {} stack {}",callStack);
}
}