Which is the difference between AtomicReference and Synchronized?

前端 未结 3 1142
独厮守ぢ
独厮守ぢ 2021-02-07 22:48

Is there any difference between AtomicReference and Synchronized?
E.G.

public class Internet {
    AtomicReference address;
    public String g         


        
3条回答
  •  伪装坚强ぢ
    2021-02-07 23:29

    There's nothing wrong with the other answers here if you can understand them, but they mostly seem to focus on details, nomenclature, and use-cases, while skipping over the big picture that "everybody" already knows.

    Here's the big picture---the difference between an AtomicFoobar operation and a synchronized block.

    An AtomicFoobar operation (e.g., atomicReference.compareAndSet(...)) either performs exactly one, very simple, thread-safe operation, or else it fails. Regardless of whether it succeeeds or fails, it will never make the thread wait.

    A synchronized block, on the other hand is as complicated as you make it---there is no limit to how many statements are executed while the lock is locked. A synchronized block will never fail, but it may make the calling thread wait until the operation(s) can be safely performed.

    On most architectures, each AtomicFoobar methods is implemented as a Java native method (i.e., C code) that executes a single, specialized hardware instruction. Synchronized, on the other hand is most always implemented with operating system calls which, somewhere deep in the guts, probably make use of the same hardware instructions.

提交回复
热议问题