Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should a db connection be a singleton?

Tags:

What is the best way in Java to create a singleton? Should a DB connection be a singleton (being a singleton it's automatically thread-safe)? Because theoretical the DB can't be accessed by many users in the same time.

like image 425
spauny Avatar asked Jun 28 '11 14:06

spauny


People also ask

When should something be a singleton?

A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

What's the downside of singleton?

Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.

Why use a singleton instead of static methods?

Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.


2 Answers

A DB connection should not normally be a Singleton.

Two reasons:

  1. many DB drivers are not thread safe. Using a singleton means that if you have many threads, they will all share the same connection. The singleton pattern does not give you thread saftey. It merely allows many threads to easily share a "global" instance.
  2. Personally, I think Singleton often leads to bad design: See this post (by somebody else) http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/

Instead of doing this consider a database pool. The pool is shared (and could be a singleton if you wanted). When you need to do database work your code does this:

getConnectioFromPool();  doWork() closeConnection() // releases back to pool 

Sample Pool Libraries:

  • http://commons.apache.org/dbcp/
  • http://jolbox.com/
like image 155
Dave Avatar answered Sep 18 '22 16:09

Dave


The best way to create a singleton (as of today) is the enum singleton pattern (Java enum singleton)

I doubt, that a Singleton is necessary or of any value for a database connection. You probably want some lazy creation: a connection is created upon first demand and cached, further requests will be fullfilled with the cached instance:

public ConnectionProvider {   private Connection conn;    public static Connection getConnection() {     if (conn == null || conn.isClosed()) {       conn = magicallyCreateNewConnection();     }     return conn;   } } 

(not thread safe - synchronize, if needed)

like image 44
Andreas Dolk Avatar answered Sep 19 '22 16:09

Andreas Dolk