How to find out how long a thread has been idle

Short version. In java, is there a way to find out how long the thread has been idle? If that matters, the objects I'm accessing are sent to the idle state by calling condition.await() .

Long version: (this is a home issue)

I am working on a program that creates 10 supplier threads and 10 consumer threads, with a synchronous common โ€œconference roomโ€. Consumer streams sleep a bit, produce a random number and (if the data field in the conference room is empty), put a random number in this field and mark it for the consumer stream with the same identifier. If the data field is not empty, they are await in a busy state. Consumer flows check to see if data is marked for them in the conference room: If not, they are await in the wrong state. If so, they save the number in the data field, set it to zero, and call Occupied.signalAll() to notify the provider threads that the data field is now empty. (Vendor threads call wrongID.signalAll() to notify consumer flows that new data is in the field).

I have some diagnostic println statements (Provider 0 enters the meeting room, leaves data / Provider 1 enters the waiting room ...), and everything seems to be working fine. I would also like to print statements when threads wake up, which shows how long they have been waiting. Is it 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 raids on multithreading)

+4
source share
1 answer

Since you cannot override wait() (it final ) or Condition (unless you create your own implementations of Lock and Condition ..), I would suggest making the simplest option.

I believe that you have code like this in your threads (for both the consumer and the provider):

 while (conditionForWaiting) { condition.await() } 

With this, you can add a timestamp with System.currentTimeMillis() before entering the while loop (if conditionForWaiting is true!). Then just type (System.currentTimeMillis()-startTime)/1000 to print the number of seconds spent waiting. Or save it in the field and get getter, no matter what you do with it.

+1
source

All Articles