When do I need to use AtomicBoolean in Java?

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

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

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 04:49

    When multiple threads need to check and change the boolean. For example:

    if (!initialized) {
       initialize();
       initialized = true;
    }
    

    This is not thread-safe. You can fix it by using AtomicBoolean:

    if (atomicInitialized.compareAndSet(false, true)) {
        initialize();
    }
    

提交回复
热议问题