Ever need to destroy a singleton instance?

chance picture chance · Mar 17, 2011 · Viewed 17.9k times · Source

By using a singleton, only one instance of it can be created. Do we ever need to destroy that instance?

I have a singleton DBManager, which manages a JDBC connection and query operations. By calling its static newInstance method, I can get the instance of it, then I do some queries. Finally, I want to close the Database connection, and I call another static method close to close the JDBC connection.

Now the connection has been closed, while the instance of DBManager is still alive but not useful. Do I need to destroy it by for example assigning it to null? Otherwise it may be referenced by mistake later on.

If I assign that instance with null, then call newInstance method again, will I get another new different instance?

Answer

Ted Hopp picture Ted Hopp · Mar 17, 2011

I wouldn't get hung up over the semantics of “singleton”—your requirement is that at most one instance of DBManager exist at any time. Once that instance is rendered useless, you can either destroy it so a fresh instance will be created on demand, or else define your newInstance method (which I might suggest be renamed getInstance) to throw an exception (perhaps IllegalStateException) if it is called after the singleton has been rendered useless.

If you are going to destroy it when rendered useless, I suggest that this be done inside the singleton class automatically, with no outside help. You also should consider completely hiding the singleton DBManager and implementing a delegation pattern instead. This will avoid the problem of a client keeping a reference to the stale DBManager instance. You can then make the delegate object a regular singleton.