Archie Cobbs wrote:
Dalibor Topic wrote:
I've implemented VMThread.holdLock in java. It's is
probably quite slow,
and wakes up the ocassional thread without much use, but
hey, it's in
java, so that's one less method to implement. OK to commit?
Java in theory guarantees that threads are woken up only when
notified via notify(), though not all VMs follow this (typically
because they rely on pthread_cond variables, which don't provide
this guarantee). So it your implementation potentially could produce
bugs in otherwise correct programs.
This is not a reason to not add it, but at the minimum a
comment should be included with a warning, etc.
Agreed.
I use a slight variant, which has a different set of problems:
static boolean holdsLock(Object obj)
{
if(obj == null)
{
throw new NullPointerException();
}
try
{
// HACK this is a lame way of doing this, but I can't see any other
way
// NOTE Wait causes the lock to be released temporarily, which isn't
what we want
if(false) throw new IllegalMonitorStateException();
if(false) throw new InterruptedException();
cli.System.Threading.Monitor.Wait(obj, 0);
return true;
}
catch(IllegalMonitorStateException x)
{
return false;
}
catch(InterruptedException x1)
{
// since we "consumed" the interrupt, we have to interrupt ourself
again
cli.System.Threading.Thread.get_CurrentThread().Interrupt();
return true;
}
}
Note that the .NET Monitor.Wait(obj, 0) waits 0 ms, not indefinitely
like Java.
I think that the (potential) temporary release of the lock isn't as bad
as a spurious notify