And the atomic class in the contract can solve the atomic problem of the compound class operation like num++, compared with the lock mechanism, the use of atomic class is more compact and lighter, and the performance cost is smaller, the following analysis the realization mechanism of atomic class.
Pessimistic solution (blocking synchronization)
We know that a num++ seemingly simple operation is actually made by 1. Read 2. Plus 13. Write three-step, which is a compound class operation ( so the volatile we mentioned earlier cannot solve the num++ atomicity problem ), In a concurrent environment, if you do not do any synchronous processing, you will have a thread security issue. The most direct way to deal with this is locking .
Synchronized (this) { num++;}
The use of exclusive locking mechanism to solve, is a pessimistic concurrency strategy, holding a "always diao people want to harm me" situation, every time the operation of the data are considered other threads will participate in competition modification, so directly lock. Only one thread can hold a lock at the same moment, and the other threads will block. A thread's pending recovery can have a significant performance overhead, although the JVM has a lot of optimizations for the acquisition and release of non-competitive locks, but once multiple threads are competing for locks, frequent blocking wakes can have a significant performance overhead . Therefore, it is not reasonable to use synchronized or other heavyweight locks to handle it.
Optimistic solution (non-blocking synchronization)
The optimistic solution, as the name implies, is very generous optimism, each time the operation of the data, it is believed that other threads will not participate in the competition modification, nor lock. If the operation succeeds, it is best; if it fails, for example, there are other threads that have entered and modified the data (relying on conflict detection), do not block, and can take some compensation mechanisms, the general strategy is to retry repeatedly. It is clear that this idea is much more reasonable than simply brute-use locks to ensure synchronization.
Since the implementation mechanism of the atomic class in the contract is not very much, we will analyze it by Atomicinteger this atom class. Let's take a look at how Atomicinteger is guaranteed to be atomic for operations such as num++.
/** * atomically increments by one of the current value. * * @return The updated value */public final int incrementandget () {for (;;) { int current = Get (); int next = current + 1; if (Compareandset (current, next)) return next; } }
Let's analyze the logic of the Incrementandget:
1. Get the current value values first
2. Add one to Value
3. The third step is the critical step of invoking the Compareandset method to perform atomic update operations, the semantics of which are:
Check that the current value is equal to present, and if it is equal, it means that value is not modified by another thread, and it is updated and returns True. If they are not equal, Compareandset returns False, and then the loop continues to attempt the update.
Compareandset calls the Compareandswapint method of the unsafe class
/** * atomically Sets the value to the given updated value * If the current value {@code = =} The expected value.
* * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * The actual value is not equal to the expected value. * /Public Final Boolean compareandset (int expect, int. update) { return unsafe.compareandswapint (this, Valueoffset, expect, update); }
The compareandswapint of unsafe is a native method, which is platform-related. It is a CPU-based CAS instruction to complete .
Public Final native Boolean compareandswapint (Object var1, long var2, int var4, int var5);
CAS (Compare-and-swap)
The CAS algorithm is directly supported by the hardware to ensure atomicity, there are three operands: memory location V, the old expected value A and the new value B, when and only if v conforms to the expected value of a, CAS atomically update the value of V with the new value B, otherwise, it does nothing.
The ABA problem in CAs
Of course, CAS is not perfect, it exists "ABA" problem, if a variable first read is a, in the compare phase is still a, but in fact, it may be in this process, it was first changed to B, and then changed back to a, and CAS is not aware of the problem. CAs only focuses on whether the values before and after the comparison change, not the details of the variables in the process, which is known as the ABA loophole.
Analysis of the implementation principle of Java Atom class