Combine
Combine

Reputation: 4224

How can I measure thread waiting time?

I couldn't find out how to measure the time that a Thread is waiting locked. I have to determine if a Thread is waiting locked more than 1 second and if so to run another Thread instead. Thanks!

Upvotes: 4

Views: 5082

Answers (3)

N V Harikrishna
N V Harikrishna

Reputation: 31

Generally the methods which operates on locks accepts timeout as an argument. If you are using wait(), you can specify the amount of time by passing time to wait as argument. Check here for more details: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28long%29.

If you are using Lock, then try tryLock method of it which accepts time it has to wait. Check this tutorial for an idea: http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68857

Time it using Sytem.nanoTime(); just before and after the wait.

long start = System.nanoTime();
wait();
long time = System.nanoTime() - start; // nanos

Or:

long start = System.nanoTime();
synchronized (objHere)
{
    long time = System.nanoTime() - start; // nanos
    // ...
}

Note: If a Thread is locked, the scheduler will continue with other Threads. You don't have to do this manually. That is the idea of threads. Maybe you are facing a deadlock? Wikipedia says it nicely:

A deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does.

Upvotes: 2

Shailendra Madda
Shailendra Madda

Reputation: 21551

Try this:

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = endTime - startTime;

Upvotes: 3

Related Questions