Is a volatile int in Java thread-safe?

后端 未结 6 1645
北荒
北荒 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条回答
  •  萌比男神i
    2020-11-27 03:18

    [...] as in being able to be safely read from and written to without locking?

    Yes, a read will always result in the value of the last write, (and both reads and writes are atomic operations).

    A volatile read / write introduces a so called happens-before relation in the execution.

    From the Java Language Specification Chapter 17: Threads and Locks

    A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.

    In other words, when dealing with volatile variables you don't have to explicitly synchronize (introduce a happens-before relation) using synchronized keyword in order to ensure that the thread gets the latest value written to the variable.

    As Jon Skeet points out though, the use of volatile variables are limited, and you should in general consider using classes from the java.util.concurrent package instead.

提交回复
热议问题