Monitoring lock contention on Java applications

主宰稳场 提交于 2020-01-01 03:39:07

问题


I am trying to create a little benchmark (in Groovy) that shows high thread contention on a couple of synchronized methods. High contention should show up when monitoring voluntary context switches, and in Linux this can be achieved thanks to "pidstat".

The program is the following:

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 "========================="

}

but the command

pidstat -w -I -p 26848 5

is printing 0 on the voluntary context switches column. The program creates 100000 thread that concurrently access a synchronized method. I can't believe that with such workload, no context switching is happening.

What's wrong with my benchmark?


回答1:


Your command displays statistics for the main thread only, child PIDs are not counted.

Hotspot JVM has internal synchronization counters, but some magic is needed in order to unlock them:

  1. Run jconsole.exe -J-Djconsole.showUnsupported and connect to your JVM.
  2. Select Connection -> Hotspot MBeans -> Create from the main menu.
  3. Open sun.management.HotspotRuntime on the MBeans tab.
  4. You'll find a bunch of counters under InternalRuntimeCounters attribute:
    • sun.rt._sync_ContendedLockAttempts
    • sun.rt._sync_Parks
    • sun.rt._sync_Notifications
    • sun.rt._sync_Inflations
      etc.


来源:https://stackoverflow.com/questions/22749700/monitoring-lock-contention-on-java-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!