Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a singleton in java for try-with-resource purposes

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?

like image 765
mat_boy Avatar asked Apr 12 '26 00:04

mat_boy


2 Answers

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.

like image 139
Zim-Zam O'Pootertoot Avatar answered Apr 13 '26 14:04

Zim-Zam O'Pootertoot


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.

like image 32
Lucia Pasarin Avatar answered Apr 13 '26 13:04

Lucia Pasarin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!