hanhu hanhu - 5 months ago 37
Java Question

USing a Singleton class for Database Connection

If i write a Singleton class for obtaining a Database connection .

Now my question is , Assume that there are 100 Usrs accessing the Application , and if one user closes the connection , for the other 99 users will the connection would be closed or not ??

This is my Sample Program which uses Singleton class for getting Database Connection

public class GetConnection

private GetConnection()

public Connection getConnection()
Context ctx = new InitialContext();
DataSource ds = ctx.lookup("jndifordbconc");
Connection con = ds.getConnection();
return con ;

public static GetConnection getInstancetoGetConnection ()
// which gives GetConnection class instance to call getConnection() on this .

Please guide me .


As long as you don't return the same Connection instance on getConnection() call, then there's nothing to worry about. Every caller will then get its own instance. As far now you're creating a brand new connection on every getConnection() call and thus not returning some static or instance variable. So it's safe.

However, this approach is clumsy. It doesn't need to be a singleton. A helper/utility class is also perfectly fine. Or if you want a bit more abstraction, a connection manager returned by an abstract factory. I'd only change it to obtain the datasource just once during class initialization instead of everytime in getConnection(). It's the same instance everytime anyway. Keep it cheap. Here's a basic kickoff example:

public class Database {

    private static DataSource dataSource;

    static {
        try {
            dataSource = new InitialContext().lookup("jndifordbconc");
        catch (NamingException e) { 
            throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);

    public static Connection getConnection() {
        return dataSource.getConnection();


which is to be used as follows according the normal JDBC idiom.

public List<Entity> list() throws SQLException {
    List<Entity> entities = new ArrayList<Entity>();

    try (
        Connection connection = Database.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
        ResultSet resultSet = statement.executeQuery();
    ) {
        while (resultSet.next()) {
            Entity entity = new Entity();

    return entities;

See also: