Atomic Operations and multithreading

后端 未结 6 1337
一整个雨季
一整个雨季 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:31

    You need an AtomicInteger if you need to read a variable and write a result depending on the read value. For instance, i++ reads i (e.g. 3) and writes i+1 (e.g. 4). A thread may be interrupted meanwhile, and three other threads increment i too. Now that we get back, i actually has the value 6 but our thread still writes 4, based on what it read beforehand.

    AtomicInteger.getAndIncrement ensures you're not interrupted and therefore always incrementing properly. Moreover, the result is always flushed into memory, whereas a non-volatile i might not be flushed to memory. In this case other threads might not even see the changes.

提交回复
热议问题