When do I need to use AtomicBoolean in Java?

前端 未结 5 1777
情话喂你
情话喂你 2020-12-02 03:55

How I can use AtomicBoolean and what is that class for?

5条回答
  •  感情败类
    2020-12-02 04:45

    There are two main reasons why you can use an atomic boolean. First its mutable, you can pass it in as a reference and change the value that is a associated to the boolean itself, for example.

    public final class MyThreadSafeClass{
    
        private AtomicBoolean myBoolean = new AtomicBoolean(false);
        private SomeThreadSafeObject someObject = new SomeThreadSafeObject();
    
        public boolean doSomething(){
             someObject.doSomeWork(myBoolean);
             return myBoolean.get(); //will return true
        }
    }
    

    and in the someObject class

    public final class SomeThreadSafeObject{
        public void doSomeWork(AtomicBoolean b){
            b.set(true);
        }
    }
    

    More importantly though, its thread safe and can indicate to developers maintaining the class, that this variable is expected to be modified and read from multiple threads. If you do not use an AtomicBoolean you must synchronize the boolean variable you are using by declaring it volatile or synchronizing around the read and write of the field.

提交回复
热议问题