Monday, January 31, 2005

Variation on Double-checked locking


The problems with the double checked locking idom are documented here.



I propose the following as a variation when it can't be refactored in other ways. I still need to investigate if this variation actually protects from pipeline optimization.




public class HeavySingleton {

private static HeavySingleton instance;
private static Object lock = new Object();

/**
* Only permit instance access via factory method(s).
*/
private HeavySingleton() {
}

public static HeavySingleton instance() {
if (instance == null) {
synchronized (lock) {
// Does this protect from parallelism?
HeavySingleton temp = instance;
if (temp == null) {
temp = new HeavySingleton();
instance = temp;
}
}
}
return instance;
}
}



Other options:



  • if a class is always going to be used, then lazy instantiation is really pointless


  • create a factory class with synchronized methods


  • if this is an early optimization, and premature optimization is the root of all evil...



willCode4Beer

permalink
Links to this post

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home

Links to this post on: