Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  }
}
like image 527
rxg Avatar asked Jun 04 '14 09:06

rxg


People also ask

Why do we need default method in Java 8 interfaces?

Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces.

Can we override default method of interface Java 8?

A default method cannot override a method from java.

Can Java 8 default method override equals Hashcode and Tostring?

Answer: The methods declared in java. lang. Object class can not be override in Java 8 default methods.

What is Java Util Concurrent locks?

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.


1 Answers

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.

like image 95
rxg Avatar answered Sep 28 '22 05:09

rxg