This content has been marked as final. Show 6 replies
1. You don't need lazy instantiation. Just eagerly instantiate it and save yourself some headaches.
2. If you're going to lazily instantiate, then:
2a. You can simply synchronize the getInstanceMethod. I can almost guarantee you the synchronization overhead will not hurt your perfrormance.
2b. You can use a nested class to hold the instance. Google for java nested class singleton or something like that, but I'm not totally convinced it's guaranteed to lazy load.
2c. You can use an enum for the singleton. Google for that if you're not sure how. I don't like this approach, as I consider it a misuse of enums.
3, 4, 5, ... Infinity. You don't need lazy instantiation. Just eagerly instantiate and be done with it.
is it even necessary to synchronize access to a datasource I wonder? (at least I'm assuming there is a datasource in play here seeing the 'dataSource' variable)?
I mean I don't see any reference to datasources needing to be thread safe in the javadocs, but it seems quite useless to me if a datasource is not thread safe by design.
Note that I may have misunderstood my question. I thought you were asking about thread-safety of lazy instantiation. However, it appears you may have been asking about thread safety of using that singleton after it's instantiated, or something like that. If that's the case, I don't really know what your question is, so my initial answer, while still valid advice, may not be relevant to your actual question.
Yes my question is about connection management and multi threading. I currently am using the lazy initialization of a singleton. The problem is that I have multithreads using Future and ExecutorService. The first two threads grab the same connection object, so I am having some sort of synchronization issue. Here is a stack trace of my log showing my 2nd thread grabbing the same connection as the first. The other threads grab a new connection object.
2010-07-15 04:08:36 INFO [pool-2-thread-1] - SProcedure.build -> Building stored procedures for output
2010-07-15 04:08:36 INFO [pool-2-thread-2] - SProcedure.build -> Building stored procedures for output
2010-07-15 04:08:36 INFO [pool-2-thread-1] - DataBConnection.getConnection -> Opened database connection weblogic.jdbc.wrapper.PoolConnection_oracle_jdbc_driver_T4CConnection@c
2010-07-15 04:08:36 INFO [pool-2-thread-2] - DataBConnection.getConnection -> Opened database connection weblogic.jdbc.wrapper.PoolConnection_oracle_jdbc_driver_T4CConnection@c