Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to uniquely name an object

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.

like image 575
Raja Anbazhagan Avatar asked Oct 31 '22 12:10

Raja Anbazhagan


1 Answers

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.

like image 128
Andy Guibert Avatar answered Nov 08 '22 04:11

Andy Guibert