Re: user manual code example race condition

Vibhu Mohindra <[email protected]>
Newsgroups gmane.editors.j.devel
Message-ID <dbd20b4b-7161-849e-25c2-df98a03b1a8e__21989.2204551556$1552323255$gmane$org@gmail.com>
[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>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.