If I use a singleton class for a database connection, can one user close the connection for everybody?

Viewed 98277

I wrote a singleton class for obtaining a database connection.

Now my question is this: assume that there are 100 users accessing the application. If one user closes the connection, for the other 99 users will the connection be closed or not?

This is my sample program which uses a singleton class for getting a 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.

5 Answers

Great post, farhangdon! I, however, found it a little troublesome because once you close the connection, you have no other way to start a new one. A little trick will solve it though:

Replace if(con==null) with if(con==null || con.isClosed())

Related