Re: ID of thread that waken up by notify()
"Yao Qi" <qiyaoltc@gmail.com> wrote in message
news:m3y7jum5y6.fsf@gmail.com...
The notify method will wake up one thread waiting to reacquire the
monitor for the object. How could I know which thread is waken up by
this notify method called by another thread?
I looked at java.lang.management.* and JVMTI, but I could not find a
feasible way to achieve this. I could not find answer from google
either.
I'd be interestind in knowing why you need this.
A common pattern, that avoids race conditions, is something like
Requesting thread:
synchronize(monitor)
{
do something to indicate what you want
the worker thread to do, e.g. put an
entry in a work queue;
monitor.notify();
}
Worker thread:
while (true)
{
synchronize(monitor)
{
if (there's work to do)
{
grab it (e.g. pull the entry off the work queue)
}
else
{
monitor.wait();
}
}
do the work;
}
It's quite possible that the monitor.notify() will take place while all
worker threads are busy doing work, that is, that it won't wake up any of
them. Still, the work gets done by the first worker thread to finish its
currrent work and look for more. If you want to connect the worker thread
with the thread that made the request, a simple, reliable method is to put
the requesting and worker thread IDs in the work queue entry.