drew moore
drew moore

Reputation: 32680

How to find out how long a thread has been in the wait state

Short version: In java, is there a way to find out how long a thread has been in the wait state? If it's relevant, the objects I'm referring to are sent into the wait state by a call to condition.await().

Long version: (this is a homework problem)

I'm working on a program that creates 10 supplier threads and 10 consumer threads, with a synchronized common "meeting room." Supplier threads sleep for a bit, produce a random number, and (if the data field of the meeting room is empty), put the random number in that field and mark it for the consumer thread with the same id. If the data field is not empty, they await on an Occupied condition. Consumer threads check to see if the data in the meeting room is marked for them: If not, they await on a wrongID condition. If so, they they store the number in the data field, set it to null and call Occupied.signalAll() to notify the supplier threads that the data field is now empty. (Supplier threads call wrongID.signalAll() to notify consumer threads that new data is in the field).

I have several diagnostic println statements (Supplier 0 enters meeting room, leaves data / Supplier 1 enters waiting room...), and everything seems to be working fine. I would also like to print statements when threads wake up that displays how long they were in the wait state. Is this possible?

Also, if anyone sees any flaws in my logic here, feel free to point them out to me (this is one of my first forays into multithreading)

Upvotes: 4

Views: 1251

Answers (1)

ddmps
ddmps

Reputation: 4380

As you can't override wait() (it's final) or Condition (unless you make your own Lock and Condition implementations..), I'd suggest doing the simplest possible.

I suppose you have some code like this in your threads (both consumer and supplier):

while (conditionForWaiting) {
    condition.await()
}

With that, you can add a timestamp with System.currentTimeMillis() before entering the while loop (if conditionForWaiting is true!). Then, just print (System.currentTimeMillis()-startTime)/1000 to print the amount of seconds the thread spent waiting. Or save it to a field and have a getter, whatever you want to do with it.

Upvotes: 1

Related Questions