Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Locks AutoCloseable?

Are Locks auto-closeable? That is, instead of:

Lock someLock = new ReentrantLock();
someLock.lock();
try
{
    // ...
}
finally
{
    someLock.unlock();
}

...can I say:

try (Lock someLock = new ReentrantLock())
{
    someLock.lock();
    // ...
}

...in Java 7?

like image 311
fredoverflow Avatar asked Aug 06 '11 08:08

fredoverflow


2 Answers

I was looking into doing this myself and did something like this:

public class CloseableReentrantLock extends ReentrantLock implements AutoCloseable { 
   public CloseableReentrantLock open() { 
      this.lock();
      return this;
   }

   @Override
   public void close() {
      this.unlock();
   }
}

and then this as usage for the class:

public class MyClass {
   private final CloseableReentrantLock lock = new CloseableReentrantLock();

   public void myMethod() {
      try(CloseableReentrantLock closeableLock = lock.open()) {
         // locked stuff
      }
   }
}
like image 102
Stephen Avatar answered Nov 17 '22 18:11

Stephen


No, neither the Lock interface (nor the ReentrantLock class) implement the AutoCloseable interface, which is required for use with the new try-with-resource syntax.

If you wanted to get this to work, you could write a simple wrapper:

public class LockWrapper implements AutoCloseable
{
    private final Lock _lock;
    public LockWrapper(Lock l) {
       this._lock = l;
    }

    public void lock() {
        this._lock.lock();
    }

    public void close() {
        this._lock.unlock();
    }
}

Now you can write code like this:

try (LockWrapper someLock = new LockWrapper(new ReentrantLock()))
{
    someLock.lock();
    // ...
}

I think you're better off sticking with the old syntax, though. It's safer to have your locking logic fully visible.

like image 27
dlev Avatar answered Nov 17 '22 20:11

dlev