[Note: I'm still on abcl-1.4.0, which is what I refer to here.]
The original poster is right. And so, I always have to remember to write:
Interpreter.createInstance(); Interpreter interp = Interpreter.getInstance();
but OP's solution is faster.
Here is why there is a race. Interpreter.java looks like this:
public static synchronized Interpreter getInstance() { return interpreter; } public static synchronized Interpreter createInstance() { if (interpreter != null) return null; interpreter = new Interpreter(); ... return interpreter; }
OP's user code is:
Interpreter interpreter = Interpreter.getInstance (); if ( interpreter == null ) { interpreter = Interpreter.createInstance (); }
which is not itself surrounded by a synchronized (Interpreter.class) {...} block.
So two threads T1, T2 executing it could be scheduled in two possible ways, (where line execution is denoted by <thread, line_number>):
Schedule 1 <T1,1>, <T1,2>, <T2,1>, <T2,2>, <T2,3>, <T1,3> resulting in this T1:interpreter = null (due to Interpreter.createInstance()'s line 2): T2:interpreter = <not null>
Schedule 2 <T1,1>, <T1,2>, <T1,3>, <T2,1>, <T2,2>, <T2,3> resulting in: T1:interpreter = <not null> T2:interpreter = <not null>