Enrich the Lock interface
Pavel Rappo
pavel.rappo at oracle.com
Mon Aug 21 13:41:35 UTC 2023
Okay. Here are some relevant messages/threads I've been able to find within 5 minutes, using google.com:
* https://mail.openjdk.org/pipermail/coin-dev/2009-March/000267.html
* https://mail.openjdk.org/pipermail/core-libs-dev/2016-September/043303.html
* https://mail.openjdk.org/pipermail/discuss/2021-June/005819.html
* https://mail.openjdk.org/pipermail/amber-spec-experts/2022-October/003596.html
There are more of those. Sadly, some reside on concurrency-interest, whose archives are inaccessible at the moment, either directly or through markmail.org <http://markmail.org/>.
-Pavel
> On 21 Aug 2023, at 14:24, John Hendrikx <john.hendrikx at gmail.com> wrote:
>
> I couldn't find a discussion on openjdk, but for those interested (and to save others some searching) there is a JBS ticket:
>
> https://bugs.openjdk.org/browse/JDK-8025597
>
> --John
>
> On 21/08/2023 14:37, Pavel Rappo wrote:
>> This is suggested every once in a while. I appreciate that openjdk mailing lists are not easily searchable, but with a bit of skill, you could find a few previous discussions on the topic.
>>
>> This has also been discussed on concurrency-interest (at cs.oswego.edu <http://cs.oswego.edu/>), a dedicated mailing list for concurrency in Java. Sadly, that list has been defunct for quite some time now.
>>
>> -Pavel
>>
>>> On 21 Aug 2023, at 13:18, Albert Attard <albertattard at gmail.com> wrote:
>>>
>>> Hello.
>>>
>>> I hope all is well.
>>>
>>> Do you believe it is a bad idea to enrich the Lock interface with a set of default methods that safely release the lock once ready?
>>>
>>> Consider the following (dangerous) example.
>>>
>>> final Lock lock = new ReentrantLock ();
>>> lock.lock();
>>> /* Code that may throw an exception */
>>> lock.unlock();
>>>
>>> This example will never release the lock if an exception is thrown, as the programmer didn’t wrap this up in a try/finally.
>>>
>>> Adding a default method within the Lock interface, called withLock(Runnable) for example or any better name, would streamline this, as shown next.
>>>
>>> default void withLock(final Runnable runnable) {
>>> requireNonNull(runnable, "Cannot run a null");
>>> lock();
>>> try {
>>> runnable.run();
>>> } finally {
>>> unlock();
>>> }
>>> }
>>>
>>> The caller can now simply change the above example into the following, without having to worry about this.
>>>
>>> final Lock lock = new ReentrantLock ();
>>> lock.withLock(() -> {
>>> /* Code that may throw an exception */
>>> });
>>>
>>> We can have more variants of these default methods, as shown next.
>>>
>>> default <T> T getWithLock(final Supplier<T> supplier) {
>>> requireNonNull(supplier, "The supplier cannot be null");
>>> lock();
>>> try {
>>> return supplier.get();
>>> } finally {
>>> unlock();
>>> }
>>> }
>>>
>>> Any thoughts?
>>>
>>> With kind regards,
>>> Albert Attard
More information about the core-libs-dev
mailing list