5

I have a simple webapp that acquires connection from tomcat JDBC datasource. To track the connection usage, I'm planning to implement logging while opening and closing connection. The logging supposed to print something like this.

20151230143623.947[Thread-3] INFO  [DataSourceManager:19] Opened connection identified by id : BlahBlahBlah1
20151230143623.947[Thread-3] INFO  [DataSourceManager:19] Closed connection identified by id : BlahBlahBlah1

My open and close methods are like this.

Connection openConnection(String JNDILookupName) throws Exception {
    Connection connection = DataSourceManager.getConnection(JNDILookupName);
    logDBOperation("Opened", connection.toString());
    return connection;
}
Connection closeConnection(String JNDILookupName) throws Exception {
    connection.close();
    logDBOperation("Closed", connection.toString());
}
void logDBOperation(String operation, String connecitonName){
    logger.info(operation+" connection identified by id : "+connectionName);
}

Here I'm using connection.toString() as the Connection's unique name in the Logs. But I want to know if there is any better way to do this.

rrk
  • 15,677
  • 4
  • 29
  • 45
Raja Anbazhagan
  • 4,092
  • 1
  • 44
  • 64

1 Answers1

2

Just use the default toString() implementation on the Object superclass.

It already does this for you:

getClass().getName() + '@' + Integer.toHexString(hashCode())

The toHexString(hashCode()) will give you the unique id right there. And this is a guarantee by the JVM that it will be a unique value.

Andy Guibert
  • 41,446
  • 8
  • 38
  • 61
  • I was also planning for this aproach and then I read this document http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/ And as per this source hashCode doesnt have to be unique for every object. That's where I had to lookout for other options. – Raja Anbazhagan Jan 03 '16 at 23:17
  • @RajaAnbazhagan the chances of two `hashCode()`s for two Connections that are open at the same time being the same is next to zero. If you want to go overboard and make it 100% unique, do something like `hashCode() + '-' + System.nanoTime()`. I am able to use `hashCode()` as a unique id just fine when doing enterprise scale jdbc debugging in logs – Andy Guibert Jan 03 '16 at 23:51
  • Finally decided to go with the hexString of hashcode approach. – Raja Anbazhagan Jan 04 '16 at 00:19