Hallo, I have a singleton used in multithread environment see the code :
This is a simple registry mechanism. The user can obtain only one instance (the private static Registry registry) via the getInstance method - here I use the D Schmidt's "double checked loocking" so if two (or more) threads try to get an instance only one is created. For the rest of methods I synchronized on this (the unique registry instace) so the rest is also safe.
Do not use double-check locking for your Singleton getInstance() method. The bottom line is that double-checked locking, in whatever form, should not be used because you cannot guarantee that it will work on any JVM implementation. JSR-133 is addressing issues regarding the memory model, however, double-checked locking will not be supported by the new memory model.
Originally posted by Ed Wallen: Do not use double-check locking for your Singleton getInstance() method. The bottom line is that double-checked locking, in whatever form, should not be used because you cannot guarantee that it will work on any JVM implementation...
It is only guaranteed to work if the machine designers say so. This is not just for virtual machines but it suffers the same issue running directly on the CPU. So unless your AMD Athlon manual has information supporting this technique, it may fail even with assembly/c/c++.
Warning: Micro-optimization area ahead. Hard hat must be worn at all times.
If you expect far more calls to request() than the other methods and the size of the map isn't "too large," you can avoid synchronization for request() using copy-on-write. When the Registry needs to modify the values map, it modifies a copy instead and then swaps it in for the real one. Thus, only the modifying methods need to be synchronized.[ Updated after re-reading JLS chapter 17 which states that only long and double suffer from non-atomicity. ]
The only issue is that the JVM is not required to perform the store/write actions to main memory. Thus, it's possible that the map could be swapped out with a new one, but only the thread that performed the swap sees the effect.
Making the variable volatile solves this but is only slightly faster than synchronizing. However, it still allows concurrent access which synchronization does not, which was the point all along (for me, anyway ). [ April 11, 2005: Message edited by: David Harkness ]