Your code is broken in a way you might not expect. Here's the simplified version of the bytecode it generates, decompiled to Java:
private static boolean foo;
public static final void bar() {
Boolean var0 = Boolean.valueOf(foo);
synchronized(var0) {
foo = !foo;
}
}
So you're essentially locking on whatever object the valueOf
function returns, which in my JRE is either the TRUE
or FALSE
singletons inside the Boolean
class (this is also simplified):
public class Boolean {
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
public static Boolean valueOf(boolean var0) {
return var0 ? TRUE : FALSE;
}
}
Your best bet for certain, runtime independent code is probably to create a separate instance of Any
to synchronize on.