Volatile or synchronized for primitive type?

前端 未结 5 1523
栀梦
栀梦 2021-02-04 06:52

In Java, assignment is atomic if the size of the variable is less than or equal to 32 bits but is not if more than 32 bits.

What (volatile/synchronized) would be more ef

5条回答
  •  礼貌的吻别
    2021-02-04 07:31

    If you find locking on the object itself too heavy, then synchronized is the way to go. Prior to Java 1.5 volatile may have been a good choice, but now volatile can have a very large impact by forcing instruction ordering on the method where the assignment happens. Create a separate object (private final Object X_LOCK = new Object();) and synchronize on it when setting or getting the value of that double. This will give you a fine level of control over the locking, which it seems that you need.

    In the new concurrency package there are more options, such as AtomicReference which may be a good replacement for volatile if you really need to avoid synchronization.

提交回复
热议问题