Can AtomicInteger replace synchronized?

后端 未结 5 997
不思量自难忘°
不思量自难忘° 2020-12-31 02:21

The javadoc for the java.util.concurrent.atomic package says the following:

A small toolkit of classes that support lock-free thread-safe programm

5条回答
  •  庸人自扰
    2020-12-31 02:41

    Is volatile needed when I use AtomicInteger?

    Not necessarily. Considering your example:

    • if i is a local variable, or
    • if i is a final attribute, or
    • if the current thread and the thread that initialized (or last updated) the i variable have synchronized after that event,

    then it makes no difference if you declare i as volatile or not.

提交回复
热议问题