Vitalii Vitrenko
Vitalii Vitrenko

Reputation: 10395

Should I synchronize getConnection() of DataSource

I have this singelton with Connection Pool.

public enum ConnectionPool {
    INSTANCE;

    private DataSource ds = null;

    ConnectionPool() {
      try {
         final Context initCtx = new InitialContext();
         ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/test");
      } catch (NamingException e) {
         e.printStackTrace();
      }
    }

   public Connection getConnection() throws SQLException {
      return ds.getConnection();
   }
}

Should I synchronize getConnection() in order to prevent getting the same instance from different threads? It looks like it has been already synchronized by Tomcat but I'm not sure(I use Tomcat 8).

Upvotes: 1

Views: 1820

Answers (2)

AdamSkywalker
AdamSkywalker

Reputation: 11609

Though it is not explicitly mentioned in java docs, DataSource#getConnection method is designed to be called concurrently on a single DataSource instance.

You do not need to provide client-level synchronization in general case.

Restriction in java docs is probably omitted to provide flexibility for implementations.

Upvotes: 7

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23319

Well, you shouldn't have this "ConnectionPool" in the first place. Consider using a tested one that actually does connection pooling.

Anyways, the thread-safety of your class is that of DataSource because you delegating to it and it is the only shared state you have. There is nothing in the JDBC API that ensures thread-safety and hence you need to check the implementation details.

Upvotes: 1

Related Questions