Wednesday, June 27, 2012

One obviously knows a lot of different methods to implement singleton in java. Singleton by definition means one object per classloader. Starting Java 5 we now have enums which are first class singleton objects. The best method in java for implementing singletons is via enum(s).

Lets take a look with an example of a DB connection pool manager. We're using Data source to get connections:

public enum DBConnectionManager {
INSTANCE;

private DataSource ds = null;
private Lock connectionLock = new ReentrantLock();

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

public Connection getConnection() throws SQLException {
if(ds == null) return null;

Connection conn = null;
connectionLock.lock();
try {
conn = ds.getConnection();
} finally {
connectionLock.unlock();
}

return conn;
}
}


Since we are using connection pooling, we do not really need to close the connection and it's the responsibility of the calling code to close the connection (which actually does nothing but returns the connection back to the pool).

No comments:

Post a Comment