How to check how many threads are waiting for a synchronized method to become unlocked

折月煮酒 提交于 2019-12-05 02:14:24

You could transform your code to use a synchronized block instead of synchronized methods, here is my rough draft. I'm not sure whether it matches you second requirement (due to my choppy english)

public class Sync {
    public static int waiting = 0;
    private Object mutex = new Object();

    public void sync() {
        waiting++;
        synchronized (mutex) {
            waiting--;
            long start = System.currentTimeMillis();
            doWhatever();
            System.out.println("duration:"
                    + (System.currentTimeMillis() - start));
        }
    }
}

1) I do not believe it's possible to have this level of visibility in your code. Java provides a more powerful concurrency API which provides much more direct control and visibility. As a starting point, there's a class Semaphore which has a method getQueueLength() which sounds like it might be what you want.

2) When a synchronized method is called, the calling thread will wait until the method is unlocked, how long that takes depends on how long the code with the lock takes to do its thing. When wait()-ing on an object, you can specify a timeout. I don't believe you can do that with a synchronized method.

I think Java Thread Validator may provide some insight into these questions.

It doesn't give exactly those stats, but it does tell you how often contention happens and what the wait time is etc.

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