commit-classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Patch: Thread.holdLock implementation in java


From: Dalibor Topic
Subject: Re: Patch: Thread.holdLock implementation in java
Date: Thu, 17 Jun 2004 16:10:26 +0200
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040608

Hi Jeroen,

Jeroen Frijters wrote:
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

I'm not convinced that wait is the lesser evil.

The release of the lock can lead to a spurious deadlock, as wait just releases the locks a thread holds for the single object. If the thread holds another lock B on a different object, and the next thread acquiring the lock wants to acquire lock B as well, before it releases both locks, then we have a spurious deadlock.

Notify doesn't have that problem, as it releases no locks.

cheers,
dalibor topic




reply via email to

[Prev in Thread] Current Thread [Next in Thread]