How to uniquely name an object

I have a simple webapp that acquires a connection to datasource tomcat JDBC. To track connection usage, I plan to implement logging when opening and closing a connection. The magazine should 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 public and private methods are as follows.

 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 use connection.toString() as the unique name for Connection in the logs. But I want to know if there is a better way to do this.

+5
source share
1 answer

Just use the standard implementation of toString() in the superclass of Object .

He already does this for you:

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

toHexString(hashCode()) will give you a unique identifier. And this guarantees the JVM that it will be of unique value.

+2
source

Source: https://habr.com/ru/post/1239724/


All Articles