Search code examples
lockingjava-8default-method

Why didn't Java 8 add `withLock` default methods to the `java.util.concurrent.locks.Lock` interface?


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

Solution

  • 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.