I wanted to ask if this implementation is ok, or maybe there are some issues that can be later problematic.
The idea is to implement a ReentrantLock class that can be used with 'try with resources' and that means that it has to implement the AutoCloseable interface.
In addition, I wanted to ask why in the 'main' method the compiler yields that I have to add a 'catch' clause, because my close method (in MyReentrantLock) doesn't throw an exception.
import java.util.concurrent.locks.ReentrantLock;
public class Ex09ReentrantLock {
@SuppressWarnings("serial")
public static class MyReentrantLock extends ReentrantLock implements AutoCloseable{
public MyReentrantLock() {
super();
lock();
}
@Override
public void close(){
unlock();
}
}
public static AutoCloseable lock() {
var locker = new MyReentrantLock(); //lock() is called in the constructor
return locker; //implements AutoCloseable
}
//Demo
public static void main(String[] args) {
//try(ReentrantLock lock = new ReentrantLock()){} = compiler error
try(var locker = lock();){
//some work...
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Is this implementation ok? (call the lock in the constructor...)
Why does the compiler force me to add a catch() clause if my close doesn't throw an exception?