3

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?

mat_boy
  • 12,998
  • 22
  • 72
  • 116

3 Answers3

6

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.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • If I understood your example, I guess that `singleton` must be declared `static`! Isn't it? – mat_boy Apr 14 '13 at 17:52
  • I will accept your answer. It is more complete and has been given as first! Thank you! – mat_boy Apr 14 '13 at 17:55
  • Do you think I should move the try-with-resouce inside the getInstance() method (i.e., then I create the singleton I set the try-with-resource) – mat_boy Apr 14 '13 at 17:57
  • I ask this because this seems to not avoid multiple usage of the singleton in a try-with-resource! – mat_boy Apr 14 '13 at 17:59
  • If two thread access getinstance method at same time then there will be two object instead of one. It will break singleton rule. – Rais Alam Apr 14 '13 at 18:02
  • It depends on whether you're ever using the statement `ConnectionPool pool = MyHandler.getPool(),` i.e. whether the pool escapes MyHandler. If it does, then your current code is correct. If it doesn't, then move the try-with-resources from Main to MyHandler, and change your code such as `MyHandler.pool.dosomething` to `MyHandler.dosomething`, i.e. NEVER return the pool object from MyHandler. – Zim-Zam O'Pootertoot Apr 14 '13 at 18:03
  • @FireFly Yes, of course, but what if I do in the same Thread/main: `try(MyHandler h = MyHandler.getInstance()){ }` and then again `MyHandler h = MyHandler.getInstance()){ }`? Will `close()` be called twice? – mat_boy Apr 14 '13 at 18:04
  • Nope this is valid case close will be called once. And there will be only one istance. But I was talking about some odd scenario. Let them goes. – Rais Alam Apr 14 '13 at 18:10
1

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.

Lucia Pasarin
  • 2,268
  • 1
  • 21
  • 37
1

There are many ways to declare a class singleton but there are limitation in that approach. Best way for singleton aproach is ENUM. Declare ENUM and rest of the thing will be automatically handled.

Rais Alam
  • 6,970
  • 12
  • 53
  • 84
  • Please, can you make an example? Moreover, I have some trouble concerning the possibility to return a singleton more than once! What happens if I pass the singleton to a try-with-result block more than once? Will close() be called many times? I'm becoming to think that I need to throw an Exception if the constructor of MyHandler is called more than once! – mat_boy Apr 14 '13 at 18:02
  • Yes sure. But its too late night. We are in india i will add some example code to you tommorow with example. – Rais Alam Apr 14 '13 at 18:05
  • 1
    @mat_boy [here](http://stackoverflow.com/a/71399/1393766) you have example of ENUM used as Singleton. – Pshemo Apr 14 '13 at 18:29