Is it safe to implement a Jdbc Manager as singleton ?

Discussions

General J2EE: Is it safe to implement a Jdbc Manager as singleton ?

  1. Hi all,
    I'd like to ask your opinion about this topic:
    I have implemented my JdbcManager as a singleton,
    so I have a static instance of the class that
    releases a Connection from the pool:

    private Connection conn;
    static JdbcManager jdbc;

    public static JdbcManager getInstance() {

      if (jdbc == null) {
           jdbc = new JdbcManager();
      }

      return jdbc;

    }

    public void getConnection(String s) {

      try {
      javax.naming.Context ctx = new javax.naming.InitialContext();

      javax.sql.DataSource ds
      = (javax.sql.DataSource) ctx.lookup (s);

      conn = ds.getConnection();

      }
      catch (Exception exc) {
        exc.printStackTrace();
      }

    }

    (just to make things easier I haven't synchronized the singleton access in getInstance() )

    Is this design correct or I cannot apply the Singleton pattern to a class that releases connection from a pool? I'm afraid this will cause a bottleneck in the whole application.
    Thanks a lot
    Francesco
  2. why not let the container / app server do all the work for u i know jboss , tomcat have connection pooling in them why no just utilize them
  3. As usual, good ideas spawn on it's own from different minds! :)

    If I understood the code, as s is the name of a Datasource nothing stop you from use the Container provided Datasource (with pooling, XA support or whatever it has).

    I think that the point is to have a Service Locator to encapsulate the process of obtaining the connection from the Datasource. This is a recommended practice by Sun (check http://developer.java.sun.com/developer/restricted/patterns/ServiceLocator.html )

    This can be a bottleneck only if you are working in a distributed enviroment (ie, your JNDI provider is on another JVM/server) because building the InitialContext and retrieving the DS can be costly, but don't worry about it until you need to.

    Hope this help,

    Rafael

    PS: BTW, I guess that when you said "releases a Connection from the pool" you mean "it gets a Connection from the pool" :)