I cannot understand the purpose of writing a sequence of operations in an infinite loop.
The purpose of this code is to ensure that the volatile field is updated accordingly without the overhead of locking synchronized . If there are not a large number of threads that compete for updating the same field, this will most likely start several times to accomplish this.
The volatile keyword provides memory visibility and synchronization, but does not in itself provide atomic operations with multiple operations (testing and installation). If you test and then set the volatile field, there are race conditions if several threads try to perform the same operation at the same time. In this case, if several threads try to increase the AtomicInteger value AtomicInteger same time, you can skip one of the increments. The parallel code here uses the spin loop and the compareAndSet base methods to ensure that the volatile int updated to 4 (for example) if it is still 3.
- t1 gets an int atom and is 0.
- t2 gets the int atom and is 0.
- t1 adds 1 to it
- t1 atomizes tests to make sure it is 0, it stores 1.
- t2 adds 1 to it
- t2 atomically checks to make sure that it is 0, it is not, so it must rotate and try again.
- t2 gets the int atom and equals 1.
- t2 adds 1 to it
- t2 atomizes the tests to make sure it is 1, and stores 2.
Does it use any special purpose in the Java Memory Model (JMM).
No, it serves to define the class and method and uses JMM and language definitions around volatile to achieve its goal. JMM defines what the language does with synchronized , volatile and other keywords, and how several threads interact with cached and central memory. This is mainly about interacting with internal codes with the operating system and hardware, and rarely, if ever, about Java code.
This is the compareAndSet(...) method, which approaches JMM by calling the Unsafe class, which is mainly native methods with some shells:
public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); }
Gray
source share