----- Mail original ----- > De: "Ivan Gerasimov" <ivan.gerasi...@oracle.com> > À: "Krystal Mok" <rednaxel...@gmail.com>, "core-libs-dev" > <core-libs-dev@openjdk.java.net> > Envoyé: Samedi 3 Septembre 2016 12:23:28 > Objet: Re: A bit of sugar for j.u.c.locks with try-with-resources?
> 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. but it does an allocation (if the escape analysis fails), i think it's better to wait for proper value types :) > > With kind regards, > Ivan regards, Rémi > >> 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)