<div dir="ltr">Hello.<br><br>I hope all is well.<br><br>Do you believe it is a bad idea to enrich the <span style="font-family:monospace">Lock</span> interface with a set of default methods that safely release the lock once ready?<br><br>Consider the following (dangerous) example.<br><br><span style="font-family:monospace">final Lock lock = new ReentrantLock ();<br>lock.lock();<br>/* Code that may throw an exception */<br>lock.unlock();<br><br></span>This example will never release the lock if an exception is thrown, as the programmer didn’t wrap this up in a try/finally.<br><br>Adding a default method within the <span style="font-family:monospace">Lock</span> interface, called <span style="font-family:monospace">withLock(Runnable)</span> for example or any better name, would streamline this, as shown next.<br><br><span style="font-family:monospace">default void withLock(final Runnable runnable) {<br>    requireNonNull(runnable, "Cannot run a null");<br>    lock();<br>    try {<br>        runnable.run();<br>    } finally {<br>        unlock();<br>    }<br>}<br><br></span>The caller can now simply change the above example into the following, without having to worry about this.<br><br><span style="font-family:monospace">final Lock lock = new ReentrantLock ();<br>lock.withLock(() -> {<br>  /* Code that may throw an exception */<br>});<br></span><br>We can have more variants of these default methods, as shown next.<br><br><span style="font-family:monospace">default <T> T getWithLock(final Supplier<T> supplier) {<br>    requireNonNull(supplier, "The supplier cannot be null");<br>    lock();<br>    try {<br>        return supplier.get();<br>    } finally {<br>        unlock();<br>    }<br>}<br></span><br>Any thoughts?<br><div><div dir="ltr" class="gmail_signature" data-smartmail="gmail_signature"><div><br></div>With kind regards,<br>Albert Attard</div></div></div>