A bit of sugar for j.u.c.locks with try-with-resources?
Krystal Mok
rednaxelafx at gmail.com
Sat Sep 3 07:27:11 UTC 2016
Hi David,
Thanks for the link! I'd reckon it's been brought up before, but I guess I
didn't use the right keywords to get a good search. That's good enough
history for me. It explains every issue I've thought about.
The new Java 9 TWR syntax is still fairly limited, in that it still doesn't
support the try (locker(lock)) { ... } usage. The new TWR syntax was just
extended to allow effectively final variables in the TWR header...
Best regards,
Kris
On Sat, Sep 3, 2016 at 12:17 AM, David Holmes <david.holmes at oracle.com>
wrote:
> Hi Kris,
>
> On 3/09/2016 12:41 PM, 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.
>>
>
> Yes brought up a few times. :)
>
> https://dzone.com/articles/project-coin-try-resources
>
> If the syntax is more permissive now then it might be more feasible.
>
> Cheers,
> David
>
>
> 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()
>> }
>> }
>> }
>>
>> 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