Is there any way to check how many threads are waiting for a synchronized method to become unlocked?
I would like to know when the thread calls a synchronized method:
1) How many threads are already waiting to call the method?
2) Once the method is called how long it needed to wait for the method to become unlocked?
Solution: I solved this using stackers answer:
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));
}
}
Only one thread per instance can execute inside a synchronized instance method.
As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.
The wait function doesn't release "all locks", but it does release the lock associated with the object on which wait is invoked.
If you ever need to know this inside your Java application, you should use the holdsLock() method of java. lang. Thread class.
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.
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));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With