A bit of sugar for j.u.c.locks with try-with-resources?

Ivan Gerasimov ivan.gerasimov at oracle.com
Sat Sep 3 10:23:28 UTC 2016


Hi Krystal!

On 03.09.2016 5:41, Krystal Mok wrote:
> Hi core-libs developers,
>
> I mostly live down in the VM world, but recently I've been playing with
> j.u.c.locks a bit, and saw that there's an opportunity to retrofit the API
> with the try-with-resources syntax. I wonder if anybody has brought this
> topic up before; apologies if there had been.
>
> >From the JavaDoc of j.u.c.l.ReentrantLock, the following is a typical usage:
>
>   class X {
>     private final ReentrantLock lock = new ReentrantLock();
>     // ...
>
>     public void m() {
>       lock.lock();  // block until condition holds
>       try {
>         // ... method body
>       } finally {
>         lock.unlock()
>       }
>     }
>   }
It could be written as
    public void m() {
      lock.lock();  // block until condition holds
      try (Closeable unlocker = lock::unlock) {
        // ... method body
      }
    }

This would save a couple of lines of code.

With kind regards,
Ivan

> The try...finally construction really pops out as a try-with-resources
> candidate.
>
> So what if we retrofit that with something like:
>
>   class X {
>     private final ReentrantLock lock = new ReentrantLock();
>     // ...
>
>     public void m() {
>       try (lock.lock()) { // block until condition holds
>         // ... method body
>       }                   // automatic unlock at the end
>     }
>   }
>
> Assuming lock.lock() returns a temporary wrapper object (let's call it a
> "Locker" for this discussion), where Locker implements AutoCloseable, and
> its close() method calls lock.unlock().
> That'll make the API look and feel quite similar to the built-in
> "synchronized () { ... }" syntax. With escape analysis and scalar
> replacement implemented correctly in the VM, this temporary Locker object
> wouldn't incur much (or any) runtime cost after optimized JIT'ing, so it
> feels like a pure win to me.
>
> What do you think?
>
> Best regards,
> Kris (OpenJDK username: kmo)
>



More information about the core-libs-dev mailing list