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

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?

解决方案

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:

Run jconsole.exe -J-Djconsole.showUnsupported and connect to your JVM.

Select Connection -> Hotspot MBeans -> Create from the main menu.

Open sun.management.HotspotRuntime on the MBeans tab.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值