监视Java应用程序上的锁争用

时间:2014-03-30 20:51:11

标签: java multithreading jvm locking

我正在尝试创建一个基准测试(在Groovy中),它显示了几个同步方法的高线程争用。监控自愿上下文切换时应该出现高争用,而在Linux中,这可以通过“pidstat”来实现。

该计划如下:

class Res {

    private int n;

    synchronized public void inc() {
        n++;
        def foo = []
        for (int i = 0; i < 1000; ++i) foo << "hello"
    }

    synchronized public int getN() {
        return n;
    }

}




while (true) {

    Res res = new Res()

    int N = 100000

    for (int i = 0; i < N; ++i) {
        new Thread({ 
            res.inc() 
            if (res.getN() == N) {
                println "ok" 
            }
        }).start()
    }

    while (res.getN() < N) {

    }


    println "========================="

}

但命令

pidstat -w -I -p 26848 5

在自愿上下文切换列上打印0。该程序创建100000线程,同时访问同步方法。我无法相信,有了这样的工作量,就不会发生上下文切换。

我的基准测试有什么问题?

1 个答案:

答案 0 :(得分:6)

您的命令仅显示主线程的统计信息,不计算子PID。

Hotspot JVM有内部同步计数器,但需要一些法术才能解锁它们:

  1. 运行jconsole.exe -J-Djconsole.showUnsupported并连接到您的JVM。
  2. 选择连接 - &gt; Hotspot MBeans - &gt;从主菜单中创建
  3. MBeans 标签上打开 sun.management.HotspotRuntime
  4. 您将在 InternalRuntimeCounters 属性下找到一堆计数器:
    • sun.rt._sync_ContendedLockAttempts
    • sun.rt._sync_Parks
    • sun.rt._sync_Notifications
    • sun.rt._sync_Inflations
相关问题