This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
This works fine, but is there a chance for threading problem where Vector of user's calling DBDriver.doSelect() will be overwritten by other user's doing the same opearation? Should call to DBDriver.doSelect() be synchronized?
All right brain, you don't like me and I don't like you, but let's just do this one thing so I can get back to killing you with beer.<br /> <br />- Homer Simpson
You can safely look up the DataSource just once if you don't actually change the "clientName/conName" during the life of the program. The Connection is the one you need to acquire from the DataSource each time, but the DataSource itself is threadsafe and cachable.
The finally block is executed if the try block is entered whether or not the try block throws an exception and regardless of what happens in any of the catch blocks. Thus, you should remove the calls to closeConnection() from the catch blocks.
Vector itself is synchronized which is rarely needed. Unless you're stuck using JDK 1.0 or 1.1 or old code with Vector throughout, I recommend switching to the unsynchronized replacement: ArrayList. Check out the other collection classes as well like HashMap (instead of Hashtable), Set, etc.
[ February 02, 2005: Message edited by: David Harkness ]
Joined: Jan 24, 2001
Vector itself is synchronized which is rarely needed. Unless you're stuck using JDK 1.0 or 1.1 or old code with Vector throughout, I recommend switching to the unsynchronized replacement: ArrayList. Check out the other collection classes as well like HashMap (instead of Hashtable), Set, etc
But if I switch to unsynchronized collection, won't my code become thread unsafe? [ February 03, 2005: Message edited by: Alex Kravets ]
Joined: Aug 07, 2003
Originally posted by Alex Kravets: But if I switch to unsynchronized collection, won't my code become thread unsafe?
Only if you have multiple threads accessing the same Vector object. Note that each call to your method returns a different Vector object: "data = new Vector(50,5);".
The only way this could happen is if after the call to retrieve data -- "Vector data = DBDriver.doSelect(...)" above -- you handed the "data" Vector to multiple Threads for processing. If instead each Thread processes its own Vector, they cannot interfere with each other.
You might want to go through Sun's multi-threading tutorial to make sure you understand exactly what thread-safe and synchronization means for objects versus classes.
Think of it this way. If you have a car and I have a different car, we can both drive our cars at the same time. The "idea of a car" is not synchronized. If, however, we share a single car, then only one of us can drive it at the same time. Thus, "driving a car" is a synchronized operation on each car individually.