j.u.c.Lock with try-with-resources
Brian Goetz
brian.goetz at oracle.com
Tue Jun 1 19:33:02 UTC 2021
This is a sad story, which gets dusted off every few years and retold.
juc.ReentrantLock predates TWR, so no attempt was made to address the
problem when Lock was added to the JDK.
TWR came in via Project Coin, which had the effect of narrowly
constraining what could be done. TWR therefore approximates the most
common case, which is a resource (e.g. file handle) on which we want to
ensure cleanup. At the time TWR came in, there was discussion about
whether to retrofit ReentrantLock. There were a range of issues,
including the fact that TWR expects you to _acquire_ the resource in the
TWR header, and the fact that you are not really "closing" the lock.
The scheme you suggest, where the resource is not the lock but a "lock
ticket", was rejected because the object allocation was deemed too
expensive in the context of the critical sections that are usually
guarded by locks.
The new fact is that Valhalla may be able to make that ticket creation
cheaper. So this is something we could consider once Valhalla lands.
On 6/1/2021 2:07 PM, Markus Knetschke wrote:
> Hi,
>
> I like to open a discussion about TWR support for j.u.c.Lock.
> There were already multiple threads about this but I think now with
> Valhalla & Lilliput trying to get rid of the object monitor and Loom
> also having problems with the monitor the incentive to use Lock is
> higher than ever.
> So I think it's again time to discuss the TWR friendliness, either
> through a new Lock class (which would not be my preferred way) or the
> extension of the Lock interface.
>
> One example I could think of would be an addition of:
> interface CloseableLock extends AutoCloseable {
> void close();
> }
>
> default CloseableLock autoLock() {
> lock();
> return this::unlock;
> }
>
> Implementations of this could avoid the allocation by implementing
> CloseableLock and returning "this" instead.
>
> This would take one pain point of not using object monitors with
> synchronized blocks away and get rid of the missed unlocks I sometimes
> see.
>
> Best regards,
> Markus Knetschke
More information about the discuss
mailing list