| Author |
object synchronization
|
diego rossi
Greenhorn
Joined: Jan 05, 2003
Posts: 2
|
|
Hi. Please consider this piece of code: public class JndiUtilities{ /** Internal configuration object storing information about initial context, datasources, etc*/ private static final Configuration configuration = ConfigurationProvider.getConfiguration(); /** Internal map where to store objects obtained via jndi for reusing instances*/ private static final Map map = new HashMap(); // HERE WE STORE WITH SPECIAL KEYS JNDI RESOURCES TO BE CACHED; // WE OBTAIN MAP'S LOCK FOR BEING SURE TO AVOID CONCURRENT IDENTICAL OPERATION ON IT (QUIET IMPOSSIBLE, INVISIBLE OVERHEAD) private static void storeResource(String key, Object resource){ synchronized(map){ if( ! map.containsKey(key) ){ map.put(key, resource); } } } private static Object getResource(String key){ // HERE WE TRY TO RETRIEVE WITH SPECIAL KEYS JNDI RESOURCES ALREADY CACHED; synchronized(map){ Object object = null; if( map.containsKey(key) ){ object = map.get(key); } return object; } } Multiple threads access JndiUtilities class, retrieving jndi resources (thanks to other methods not reported here) then stored in a shared internal map. My goal is to have only a single thread per time to execute multiple operation on this internal map, so in methods getResource/setResource I force these multiple thread to obtain the lock on the map. I would like to know if you find this simple design correct, and if you think there can be other solutions. For example, are there any differences in synchronizing directly getResource/setResource methods ? Thank you very much, bye from Italy.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24041
|
|
Welcome to Java Ranch! Your design is fine, although perhaps a bit verbose. In particular, your getResource() method could be written identically as Synchronizing on map and synchronizing the static methods themselves would have basically the same effect. One advantage of synchronizing on the provate map is that other code can't inadvertently get in the way of your locks. Synchronized methods lock the class object itself, so other code could in that case potentially interfere. P.S. -- Note that you can use the [code] UBB tag to make the code you post come out nicely formatted. [ August 26, 2003: Message edited by: Ernest Friedman-Hill ]
|
[Jess in Action][AskingGoodQuestions]
|
 |
diego rossi
Greenhorn
Joined: Jan 05, 2003
Posts: 2
|
|
Thankyou very much for the fast and clear answer. I will 'study' ubb tag for future posts on these forums. Bye.
|
 |
Dana Hanna
Ranch Hand
Joined: Feb 28, 2003
Posts: 227
|
|
|
Note - Ernest forgot to put "return" in his code... Hopefully it's assumed. I agree with everything else...
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: object synchronization
|
|
|