gpt4 book ai didi

Java 线程分析 : Determine Thread waits for specific locks and duration of each wait

转载 作者:行者123 更新时间:2023-11-30 09:56:26 26 4
gpt4 key购买 nike

我有一个使用线程的 Java 应用程序,它使用多个 Lock 对象实例来同步对公共(public)资源的访问。

现在,作为性能测量的一部分,我想测量每个线程在每个锁中花费的时间。到目前为止,我已经尝试过 NetBeans 探查器。

Netbeans 探查器向我显示线程的总等待时间,但无法知道线程等待锁的时间。

对于这种测量,您会推荐哪种工具?

干杯

最佳答案

根据您需要的具体数据,您可以从 Java 程序中获取这些信息。例如,像这样的东西将每秒对持有的锁进行 20 次采样,持续 100 秒,从而有效地创建一个锁 > 近似锁定时间(给定锁被锁定的“滴答”数)的映射:

private static void runProfile() {
try {
final int noSeconds = 100;
final int sleepMillis = 50;
final int noSamples = noSeconds * 1000 / sleepMillis;

ThreadMXBean thb = ManagementFactory.getThreadMXBean();
Map<String,Integer> blockCounts = new HashMap<String, Integer>(50);
for (int i = 0; i < noSamples ; i++) {
long[] ids = thb.getAllThreadIds();
ThreadInfo[] infs = thb.getThreadInfo(ids, 0);
for (ThreadInfo ti : infs) {
LockInfo lockInf = ti.getLockInfo();
if (lockInf != null) {
String key = lockInf.toString();
Integer cnt = blockCounts.get(key);
blockCounts.put(key, cnt == null ? 1 : cnt+1);
}
}

Thread.sleep(sleepMillis);
}

System.out.println("Locks:");
for (String lockName : blockCounts.keySet()) {
System.out.println(lockName + " : " + blockCounts.get(lockName));
}
} catch (InterruptedException iex) {
Thread.currentThread().interrupt();
}
}

根据需要适应收集数据。

然后您可以在后台线程中开始此操作,例如:

    Thread thr = new Thread() {
public void run() {
runProfile();
}
};
thr.setPriority(Thread.MAX_PRIORITY-1);
thr.start();

关于Java 线程分析 : Determine Thread waits for specific locks and duration of each wait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2362409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com