Uses of volatile without synchronization

后端 未结 3 784
长情又很酷
长情又很酷 2021-01-11 14:15

Knowing that

Reads and writes are atomic for all variables declared volatile

Question1: Can this be understood

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-11 15:01

    x++; operation is atomic?

    No. This reduces to x = x + 1. The read of x is atomic, and the write to x is atomic, but x = x + 1 as a whole is not atomic.

    I wonder under what circumstances (if any) it is possible to see a variable marked volatile and not see any methods of blocks marked synchronized (that attempt to access/ modify the variable)?

    Well, there are all kinds of approaches to concurrency that don't use synchronized. There's a wide variety of other locking utilities in Java, and lock-free algorithms that still require things like volatile: ConcurrentLinkedQueue is a specific example, though it makes extensive use of "magical" compareAndSet atomics.

提交回复
热议问题