Fwd: user manual code example race condition

Vibhu Mohindra vibhu.mohindra at gmail.com
Sun Mar 17 21:35:26 UTC 2019


I had posted this from a BnB whose IP had a reputation for being a
spammer. The mailing list discussion may have moved past where this is
useful, but let me send it again anyway (from a proper IP this time).
Apologies to anybody who already received it before.

Vibhu

-------- Forwarded Message --------
Subject: Re: user manual code example race condition
Date: Mon, 11 Mar 2019 13:57:48 +0100
From: Vibhu Mohindra <vibhu.mohindra at gmail.com>
To: armedbear-devel at common-lisp.net

[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>



More information about the armedbear-devel mailing list