Is a volatile int in Java thread-safe?

后端 未结 6 1646
北荒
北荒 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:38

    Yes, you can read from it and write to it safely - but you can't do anything compound such as incrementing it safely, as that's a read/modify/write cycle. There's also the matter of how it interacts with access to other variables.

    The precise nature of volatile is frankly confusing (see the memory model section of the JLS for more details) - I would personally generally use AtomicInteger instead, as a simpler way of making sure I get it right.

提交回复
热议问题