Java – how to check how many threads are waiting for the synchronization method to unlock
•
Java
Is there any way to check how many threads are waiting for the synchronization method to unlock?
I want to know when a thread calls a synchronized method:
1) How many threads are already waiting to call the method?
2) Once a method is called, how long does it take to wait for the method to unlock?
Solution: I solved this problem with stacker:
public class LockedClass {
public static int count;
public static void measuringClass() throws IOException{
long startTime = System.currentTimeMillis();
count++;
System.out.println("Threads waiting="+count);
lockedMethod(startTime);
count--;
System.out.println("Threads waiting="+count);
}
public static synchronized void lockedMethod(long startTime) throws IOException{
System.out.println("I spent="+(System.currentTimeMillis()-startTime)+" in the queue");
Hashtable<String,String> params = new Hashtable<String,String>();
params.put("param1","test");
params.put("param2","12345678");
String sessionId = Common.getSession(Common.executeHttpRequest(params));
}
}
Solution
You can convert code to use synchronous blocks instead of synchronous methods, which is my rough draft I don't know if it meets your second requirement (due to my broken 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));
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
