Is a volatile int in Java thread-safe?

后端 未结 6 1661
北荒
北荒 2020-11-27 02:47

Is a volatile int in Java thread-safe? That is, can it be safely read from and written to without locking?

6条回答
  •  天命终不由人
    2020-11-27 03:17

    Access to volatile int in Java will be thread-safe. When I say access I mean the unit operation over it, like volatile_var = 10 or int temp = volatile_var (basically write/read with constant values). Volatile keyword in java ensures two things :

    1. When reading you always get the value in main memory. Generally for optimization purposes JVM use registers or in more general terms local memory foe storing/access variables. So in multi-threaded environment each thread may see different copy of variable. But making it volatile makes sure that write to variable is flushed to main memory and read to it also happens from main memory and hence making sure that thread see at right copy of variable.
    2. Access to the volatile is automatically synchronized. So JVM ensures an ordering while read/write to the variable.

    However Jon Skeet mentions rightly that in non atomic operations (volatile_var = volatile + 1) different threads may get unexpected result.

提交回复
热议问题