Can AtomicInteger replace synchronized?

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

    Yes, they're functionally equivalent.

    If you're in an ultra-high contention environment, you may see performance differences, but that's highly unlikely.

    0 讨论(0)
  • 2020-12-31 02:39

    They are equivalent functionally, but there is a subtle difference. synchronized has the overhead of acquiring and releasing the monitor on this, while AtomicInteger is implemented with a native method call, so it will be significantly faster.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 03:00

    AtomicInteger uses sun.misc.Unsafe underneath to perform the atomic updates.

    So, in answer to your question, yes, AtomicInteger is thread-safe.

    0 讨论(0)
提交回复
热议问题