[concurrency-interest] Re: Re: Improving RWLock compatibility - ownership test

Doug Lea dl@cs.oswego.edu
Mon, 29 Nov 2004 19:21:35 -0500

Larry Riedel:

> I prefer java.util.concurrent.locks.Lock specify the behavior
> of unlock() in this regard, instead of leaving it undefined.

Sorry. No can do. Some kinds of locks have a notion of ownership, and
some do not. Normally, read-locks do not (but see below). In a lock
without any notion of ownership, it is legal for one thread to unlock
on behalf of another. Sometimes this is desirable.  To express this,
we had to either create a subinterface, say OwnedLock, or require that
each implementation describe its policy. We chose the latter.

> java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
> implements Lock, and its 1.5.0 documentation does not seem
> to say what the behavior of its unlock is.  

Please see the class doc for ReentrantReadWriteLock, near the end:

 Implementation Notes
  A reentrant write lock intrinsically defines an owner and can only
  be released by the thread that acquired it. In contrast, in this
  implementation, the read lock has no concept of ownership, and there
  is no requirement that the thread releasing a read lock is the same
  as the one that acquired it. However, this property is not
  guaranteed to hold in future implementations of this class.

And then compare the documentation for 

Michael Mostov:

> Hence I suggest to parameterize this behavior by adding an optional
> parameter to RWLock constructor.

Thanks for the suggestion. This is probably supportable.  And as
mentioned above, we made room for this possible change in the spec,
knowing that this issue would arise. We'll look into it.  Checks for
read-holds are intrinsically expensive though, so would slow down
performance by, I'd guess, around a factor of 3. So users would need
to think hard about whether they really needed them.  (For the
curious, the most likely implementation plan is to make yet more
internal AQS classes that are attached to in constructors, and in
which there is a per-lock (not static) ThreadLocal maintaining and
checking per-thread read lock counts.)