Can AtomicInteger replace synchronized?

后端 未结 5 1006
不思量自难忘°
不思量自难忘° 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:50

    They would offer the same atomicity. The only thing you must be aware of is any time you read i you must wrap it with synchronized also

    synchronized(this){ return i;}
    

    Edit to answer your edit:

    Volatile is not necessary for your AtomicInteger. To prove that declare the AtomicInteger final. The only reason you would need the AtomicInteger to be volatile is if the AtomicInteger field itself changes. Similar to:

    volatile AtomicInteger i = new AtomicInteger(0);
    
    public void work(){
        i.incrementAndGet();
        //...do some other stuff
        i = new AtomicInteger(10);//because the field i is changing the field needs to be volatile 
    }
    

    As you can imagine that shouldn't be the case, so you shouldn't have to worry about the field being volatile.

提交回复
热议问题