...
Code Block | ||
---|---|---|
| ||
class Foo { private boolean flag = true; public void toggle() { // unsafe flag ^= true; // same as flag = !flag; } public Flagboolean getFlag() { // unsafe return flag; } } |
...
Code Block | ||
---|---|---|
| ||
class Foo { private volatile boolean flag = true; public void toggle() { // unsafe flag ^= true; } public Flagboolean getFlag() { // safe return flag; } } |
...
Code Block | ||
---|---|---|
| ||
class Foo { private volatile boolean flag = true; public synchronized void toggle() { flag ^= true; // same as flag = !flag; } public Flagboolean getFlag() { return flag; } } |
...
Code Block | ||
---|---|---|
| ||
class Foo { private AtomicBoolean flag = new AtomicBoolean(true); public void toggle() { boolean temp; do { temp = flag.get(); } while(!flag.compareAndSet(temp, !temp)); } public FlagAtomicBoolean getFlag() { return flag; } } |
...