Along the same lines as this question, I wonder why the Java team didn't add a few default methods to the Lock interface, something like this:
public default void withLock(Runnable r) {
lock();
try {
r.run();
} finally {
unlock();
}
}
This would allow a programmer to do
public class ThreadSafe {
// Object requiring protection
private final List<String> l = new ArrayList<>();
private final Lock lock = new ReentrantLock();
public void mutate(String s) {
lock.withLock(() -> l.add(s));
}
public void threadSafeMethod {
lock.withLock(() -> { System.out.println(l.get(l.size())); });
}
}
instead of
public void threadSafeMethod {
lock.lock();
try {
System.out.println(l.get(l.size()));
} finally {
lock.unlock();
}
}
Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces.
A default method cannot override a method from java.
Answer: The methods declared in java. lang. Object class can not be override in Java 8 default methods.
util. concurrent. locks Description. Interfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.
It seems like the answer to this one is similar to the answer to the linked question - it was deemed an 'attractive nuisance', due to the allocation cost of the Runnable
created from the lambda (see Brian Goetz's response to the request).
The good news is that there is an open bug for this request, which means that Oracle seems open to revisiting this decision once the JVM can reliably minimise the allocation cost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With