AtomicBoolean, set flag once, necessary? Might a static boolean be ok?

情到浓时终转凉″ 提交于 2019-12-02 09:41:39

If one thread sets the value and others read it, then volatile works fine.

If many threads may set it to true and you don't care which one actually does it, and then other thread only read it, volatile also works fine.

If many threads may set it true/false, then atomic, or synchronized, or some lock structure is the only way.

Yes, there is a performance issue with atomic, synchronized, etc. But safety usually outweighs this.

When most of the threads only reads the variable and only one of them and once will change the value you don't need to worry about the performance. AtomicBoolean is using a mechanism called CAS which now is supported by most modern processors and is a low level operation. As a result of using CAS there is almost no drawback when reading the value (which is something different from using a standard lock). With the scenario you described volatile static boolean will be enough - volatile prevents jvm from doing optimization when reading from variable, like reusing value held in register instead of checking the value in memory, so whenever a thread change the value of variable other threads will see the change. In your case both solutions will give similar if not the same performance results. Volatile will be faster than AtomicBoolean in a scenario where lot of write operation have place, but honestly I can not imagine a scenario where you have lot of writing and no one is interested in reading.

If the variable is set only once by any thread and never changes later, you can use conditional synchronized block for gaining some performance by eliminating unnecessary synchronized calls.

BUT I don't think that it worths to do. Just use AtomicBoolean or volatile variable.

public class Sandbox1 {
    private boolean status;

    public void setStatus(boolean status) {
        if (!this.status) {
            synchronized (this) {
                this.status = status;
            }
        }
    }

    public boolean isStatus() {
        if (!this.status) {
            synchronized(this) {
                return this.status;
            }
        }
        return this.status;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!