Health Center 是 IBM 提供的免費低開銷 Java 監控診斷工具與 API,運行於 IBM JVM 上。它能快速評估運行中 Java 應用狀態,協助識別並解決:記憶體洩漏、方法耗時、I/O 瓶頸、GC 調優、鎖爭用、WebSphere 即時事件、線程活動、死鎖偵測、類直方圖等問題。
https://public.dhe.ibm.com/software/isa/isa410/production/HC_Deadlock編輯 META-INF/MANIFEST.MF → Dependencies → Add:
com.ibm.java.diagnostics.healthcenter.apiorg.eclipse.uipublic class GenerateDeadlock {
static class AThread extends Thread {
Object hold, grab;
// 構造器、delay()...
private void grabLocks() {
synchronized (hold) {
delay(5000);
synchronized (grab) { delay(1000000); }
}
}
public void run() { for (int i=0; i<200000; i++) grabLocks(); }
}
private void createDeadlock() {
String s1="obj1", s2="obj2", s3="obj3";
new AThread("Thread1", s1, s2).start();
new AThread("Thread2", s2, s3).start();
new AThread("Thread3", s3, s1).start();
}
public static void main(String[] args) { new GenerateDeadlock().createDeadlock(); }
}
# Java 5 SR10+/6 SR5+/7 java -Xhealthcenter GenerateDeadlock # Java 5 SR9-/6 SR4- java -agentlib:healthcenter -Xtrace:output=healthcenter.out GenerateDeadlock
ConnectionProperties hcConn = new ConnectionProperties();(預設 localhost:1972)HealthCenter hcMon = HealthCenterFactory.connect(hcConn, true);ThreadsData hcThreadsData = hcMon.getThreadsData();hcThreadsData.deadlockDetected() 返回 booleanString[] recs = hcThreadsData.getCriticalRecommendations();public class Application implements IApplication {
HealthCenter hcMon;
public Object start(IApplicationContext context) {
ConnectionProperties hcConn = new ConnectionProperties();
hcMon = HealthCenterFactory.connect(hcConn, true);
Thread.sleep(10000); // 等待初始數據解析
checkForDeadlock();
return IApplication.EXIT_OK;
}
private boolean detectDeadlock() {
ThreadsData data = hcMon.getThreadsData();
if (data != null && data.deadlockDetected()) {
String msg = Arrays.stream(data.getCriticalRecommendations())
.collect(Collectors.joining("\n"));
new MessageBox(new Shell(new Display())).setMessage(msg).open();
return true;
}
return false;
}
void checkForDeadlock() { while (!detectDeadlock()) Thread.sleep(5000); }
}
Health Center 包含 Agent(載入目標 JVM 收集數據)與 Client(分析展示)。API 將 Client 嵌入應用,連接 Agent 獲取數據。核心類別:TestContextManager、TestContext、TestExecutionListener、ContextLoader、SmartContextLoader。
偵測到死鎖時彈出對話框顯示關鍵建議,包含死鎖線程名稱、持有/等待的鎖資訊等。
掌握 Health Center API 基礎後,可進一步開發更深度工具,查詢 GC 活動、方法分析等數據。下一部分將示範新增方法分析視圖。