Archive for February, 2010

Does this solve the broken lazy initialiser pattern?

Friday, February 19th, 2010
public class LazyFactory {
 
	private Object oUnsafe;
	private Object oSync;
 
	public Object get() {
		Object o = this.oUnsafe;
		if (o == null) {
			Object notNull = crateNewIfNeeded();
			oUnsafe = notNull;
			return notNull;
		} else {
			return o;
		}
	}
 
	synchronized Object crateNewIfNeeded() {
		if (oSync == null) {
			oSync = getExpensiveNewInstance();
		}
		return oSync;
	}
 
	/** Don't call this too often! */
	Object getExpensiveNewInstance() {
		try {
			Thread.sleep(500);
		} catch (InterruptedException ignored) {}
		return new Object();
	}
 
}

Unless I’ve done something stupid:

  1. oSync is only ever read/written inside a synchronized block which guarantees only one expensive object will be created, and that the value of oSync will always be visible between Threads.
  2. oUnsafe may be written to 100 times because the changes written by one Thread aren’t seen by another according to the Java Memory Model, but the worst that can happen is a Thread encounters synchronization.
  3. I am assuming that non-volatile writes are eventually propagated and visible by all threads, and that when this happens the Object can be got without even synchronization.