Atomic Operations and multithreading

后端 未结 6 1330
一整个雨季
一整个雨季 2020-12-13 04:47

Recently I was reading a tutorial, in that I came across a statement that says..

\"The Java language specification guarantees that reading or writing a variable is

6条回答
  •  既然无缘
    2020-12-13 05:12

    Doing a = 28 (with a being an int) is an atomic operation. But doing a++ is not an atomic operation because it requires a read of the value of a, an incrementation, and a write to a of the result. As a result, if you used a++ to implement a thread-safe counter, you could have two threads reading the value concurrently (26 for example), then have both increment it and writing it concurrently, resulting in 27 as a result, instead of 28.

    AtomicInteger solves this issue by providing atomic operations like the ones you listed. In my example, you would use incrementAndGet() for example, which would guarantee the end value is 28 and not 27.

提交回复
热议问题