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();
}
}