My aim is to use the try-with-resource construct with a single instance of a class, i.e. a singleton, that handles a pool of connections. I need this to ensure that the connection pool is closed at the end of everything, then I wanna use try-with-resource. E.g.
public class MyHandler implements java.io.Closeable{
public static ConnectionPool pool;
//Init the connection pool
public MyHandler(){
pool = ...;
}
@Override
public void close() {
pool().close();
}
}
where a possible main is:
public static void main(String [] args){
try(MyHandler h = new MyHandler){
//execute my code
// somewhere I do MyHandler.pool.something();
}
}
How can I ensure that the MyHandler is used as singleton?
The usual way I've seen of ensuring that a class is a singleton is to set its constructor to private and then use a public static getInstance method to retrieve the singleton.
public class MyHandler implements java.io.Closeable {
private static MyHandler singleton = new MyHandler();
private MyHandler() {}
public static MyHandler getInstance() {
return singleton;
}
@Override
public void close() {
//close stuff
}
}
try(MyHandler h = MyHandler.getInstance()){ }
The Spring Framework also has a nice system for defining singletons.
If what you need is a singleton class, you should make your constructor private and create a public method called getInstance() and a private attribute MyHandler instance (or whatever name you want). Then, the getInstance method calls the constructor "MyHandler()" if instance is null or not defined. And finally, it returns the instance attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With