The problem of synchronization is put forward
Suppose we use a dual-core processor to execute a and b two threads, the kernel 1 executes a thread, and the kernel 2 executes the B thread, and the two threads now have to add 1 to the member variable I of the object named obj, assuming that I has an initial value of 0, and theoretically two threads running after I value should be 2. But in fact it is possible that the result is 1.
We now analyze the reason, here for the sake of simplicity of analysis, we do not consider the situation of caching, in fact, there is a cache will increase the likelihood that the result is 1. A thread reads the in-memory variable i into the kernel 1 arithmetic unit, then adds 1 operations, and then writes the result back into memory, because the above operation is not atomic, as long as the B thread reads the value of I in memory (i value is 0) before the value of the A thread adds I 1 to memory. Then there must be a result of I which is 1. Because the A and B threads read the value of I as 0, two threads add 1 to it, and two threads write 1 to the variable i.
The most common workaround is that the code for I plus 1 in two threads locks the obj object with the Synchronize keyword. Today we present a new solution that uses the related classes in the atomic package to solve the problem.
Atomic Support on hardware
In a single-processor system (uniprocessor), actions that can be done in one instruction can be considered "atomic operations," because interrupts can only occur between instructions (because the thread's schedule needs to be completed by interruption). This is also some CPU instruction system introduced the Test_and_set, Test_and_clear and other directives for critical resource mutual exclusion reasons. In a symmetric multiprocessor (symmetric multi-processor) architecture, it is different because multiple processors in the system are running independently, even operations that can be done in a single instruction may be disturbed.
On the x86 platform, the CPU provides a means of locking the bus during instruction execution. The CPU chip has a lead #hlock pin, if the assembly language program in a command prefix "LOCK", after the assembly of the machine code so that the CPU in the execution of this instruction at the time of the #hlock pin to pull down, continue to the end of this instruction to release, So that the bus lock, so that the other CPU on the same bus temporarily can not access the memory through the bus, to ensure that this instruction in the multi-processor environment of atomicity. Of course, not all commands can be prefixed with the lock prefix, only add, ADC, and, BTC, BTR, BTS, Cmpxchg,dec, INC, NEG, not, OR, SBB, SUB, XOR, XADD, and xchg directives can be Add "LOCK" instruction to achieve atomic operation.
The core operation of Atomic is the CAS (compare and set, which is implemented using the CMPXCHG directive, which is an atomic instruction), which has three operands, the memory value of the variable v (abbreviation of value), the current expected value of the variable e (exception abbreviation), The variable wants to update the value u (abbreviation for update), and when the memory value is the same as the current expected value, overwrite the memory value with the updated value of the variable, and execute the pseudo code as follows.
if (V = = E) {= Ureturn true}else{ return false}
Now we're going to use CAs to solve these problems. The B thread reads the In-memory variable i into a temporary variable (assuming that the value read at this time is 0), and then reads the value of I into the Core1 arithmetic unit, followed by the 1 operation, comparing the value in the temporary variable with the current value of I, if the result in the same operation cell (i.e. i+ 1) After the value overrides the value of I in memory (note that this part is the CAS operation, it is an atomic operation, cannot be interrupted and CAS operations in other threads cannot be performed concurrently), otherwise the instruction execution fails. If the instruction fails, it indicates that the a thread has added the value of I to 1. It can be concluded that if the value of I at the beginning of the two thread reads is 0, then only one thread's CAS operation will succeed, because CAS operations cannot be executed concurrently. For a thread that failed the CAS operation, it would be successful if the CAS operation was performed in a loop. It can be seen that there is no thread blocking, which is fundamentally different from the principle of synchronize, and because CAs consumes a very short time, so the synchronization efficiency is very high.
Atomic Package Introduction and source code Analysis
The basic feature of a class in a atomic package is that in a multithreaded environment, when multiple threads operate on a single (both basic type and reference type) variable, only one thread succeeds and is not interrupted by another thread when multiple threads simultaneously update the value of the variable. An unsuccessful thread can continue to try and wait until execution succeeds, just like a spin lock.
The core method in the class of the atomic series calls several local methods in the unsafe class, and we need to know that a thing is the unsafe class first. The full name is: Sun.misc.Unsafe, this class contains a lot of operations on C code, including a lot of direct memory allocation and atomic operation of the call, and it is marked as non-secure, is to tell you that there are a number of method calls inside the security risks, need to be careful to use, otherwise it will lead to serious consequences, such as through UNSA When FE allocates memory, it may cause some problems like C + + to cross over to other processes if you specify certain areas.
Classes in the atomic package can be divided into 4 groups according to the data type of the operation
- Atomicboolean,atomicinteger,atomiclong
Atomic operations for thread-safe basic types
- Atomicintegerarray,atomiclongarray,atomicreferencearray
An atomic operation of a thread-safe array type that does not manipulate the entire array, but rather a single element in the array
- Atomiclongfieldupdater,atomicintegerfieldupdater,atomicreferencefieldupdater
Thread-safe operation based on basic types in Reflection principle objects (Long Integer, Integer, and reference types)
- Atomicreference, Atomicmarkablereference,atomicstampedreference
Thread-safe reference types and atomic manipulation of reference types that prevent ABA problems
Our commonly used Atomicinteger, atomicreference, and atomicstampedreference are integer and reference types, and now let's analyze the Atomicinteger source code in the atomic package, Other classes of source code are basically basically similar.
1. Parametric constructors
Public Atomicinteger (int initialvalue) { = initialvalue;}
As can be seen from the constructor function, values are stored in the member variable value
Private volatile int value;
The member variable value is declared as a volatile type, which describes the visibility under multithreading, that is, any modification of a thread that is immediately visible in other threads
2. Compareandset method (value values are passed through internal this and valueoffset)
Public Final boolean compareandset (intint update) { return Unsafe.compareandswapint (This, Valueoffset, expect, update);}
3. Getandset method, which calls the Compareandset method in the method
Public Final int getandset (int newvalue) { for (;;) { int current = get (); if (Compareandset (current, newvalue)) return Current ; }}
If other threads change the value of value before executing if (Compareandset (current, NewValue), then the value of value must be different from current value, Compareandset execution fails, You can only regain the value of values, and then continue the comparison until successful.
4. Implementation of i++
Public Final int getandincrement () { for (;;) { int current = get (); int Next = current + 1; if (Compareandset (current, next)) return Current ; }}
5. Implementation of ++i
Public Final int Incrementandget () { for (;;) { int current = get (); int Next = current + 1; if (Compareandset (current, next)) return next;} }
Using the Atomicinteger example
The following procedure, the use of Atomicinteger simulation selling procedures, the results of the operation will not appear in two programs sold the same ticket, will not be sold to a negative vote
Packagejavaleanning;ImportJava.util.concurrent.atomic.AtomicInteger; Public classSelltickets {Atomicinteger Tickets=NewAtomicinteger (100); classSellerImplementsrunnable{@Override Public voidrun () { while(Tickets.get () > 0){ intTMP =Tickets.get (); if(Tickets.compareandset (TMP, tmp-1) {System.out.println (Thread.CurrentThread (). GetName ()+" "+tmp); } } } } Public Static voidMain (string[] args) {Selltickets St=Newselltickets (); NewThread (St.NewSeller (), "Sellera"). Start (); NewThread (St.NewSeller (), "Sellerb"). Start (); }}
ABA Issues
The above example runs perfectly correctly, based on the fact that two (or more) threads are manipulating the data in the same direction, and the above example two threads are tickets. For example, multiple threads to a shared queue into the row into row operation then through the Atomicreference class can also get the correct results (the queue maintained in Aqs is actually the case), but multiple threads can be into row can also be out, that is, the data operation direction is inconsistent, Then there may be an ABA situation.
We now take a good example to explain the ABA problem, assuming there are two threads T1 and T2, these two threads on the same stack on the stack and into the stack operation.
We use atomicreference defined tail to save the top position of the stack.
atomicreference<t> Tail;
Assuming that the T1 thread is ready for the stack, we only need to update the top position of the stack from the SP through the CAS operation to NEWSP for the stack operation, as shown in 1. However, before the T1 thread executes Tail.compareandset (SP, NEWSP), the system is thread-dispatched and the T2 thread begins execution. T2 performed three operations, a out stack, b out of the stack, and then a into the stack. At this point the system starts to dispatch again, the T1 thread continues to perform the stack operation, but for the T1 thread, the top element of the stack is still a, (that is, T1 still thinks B is the next element of Stack top a), which is actually shown in case 2. T1 will assume that the stack has not changed, so Tail.compareandset (sp, newsp) succeeds, and the top pointer is pointed to the B node. In fact, B is no longer present in the stack, and T1 the result of a stack 3, which is obviously not the correct result.
The solution of ABA problem
Use Atomicmarkablereference,atomicstampedreference. Use the above two atomic classes to operate. In addition to comparing the current and expected values, they will be able to compare (manipulate) The stamp value when implementing the compareandset instruction, and the Compareandset method will succeed when both the expected value and the (operating) stamp value are all together. Each update success stamp value is changed, and the setting of the stamp value is controlled by the programmer.
Public boolean compareandset (v expectedreference, v int expectedstamp,int Newstamp ) { pair<V> current = pair; return Expectedreference = = Current.reference && Expectedstamp = = current.stamp && = Current.reference && Newstamp = = Current.stamp) | | Caspair (Current, Pair.of (Newreference, Newstamp)));}
At this time the Compareandset method requires four parameters expectedreference, newreference, Expectedstamp, Newstamp, we use this method to ensure that the expected stamp value and to update the stamp value can not be the same, usually Newstamp = Expectedstamp + 1
Also take the above example
Assume that the thread T1 before the stack: SP points to a, and the stamp value is 100.
Thread T2 execution: When a is out of stack, SP points to B and the stamp value becomes 101.
b after the stack, the SP points to C, the stamp value becomes 102,
After a is in the stack, the SP points to a, and the stamp value becomes 103.
The thread T1 continues execution of the Compareandset statement, discovering that the SP is still pointing to a, but the expected value of the stamp value differs from the current value, so the compareandset fails, from the new fetch of the NEWSP value (newsp points to C at this point), and the expected value of the stamp. The compareandset operation is then performed again, so that a succeeds the stack, and the SP points to C.
Note that since Compareandset can only change one value at a time, newreference and Newstamp cannot be changed at the same time, when implemented, a class pair class is defined internally to turn newreference and Newstamp into an object, When doing CAS operations, it is actually the operation of the pair object
Private Static classPair<t> { FinalT Reference; Final intStamp; PrivatePair (T Reference,intstamp) { This. Reference =reference; This. Stamp =Stamp; } Static<T> pair<t> of (T reference,intstamp) { return NewPair<t>(reference, stamp); }}
For atomicmarkablereference, the stamp value is a variable of type Boolean, while the Atomicstampedreference stamp value is an integer variable.
Reference content
[1] http://my.oschina.net/cloudcoder/blog/359291
[2] http://hustpawpaw.blog.163.com/blog/static/184228324201210811243127/
[3] Http://baike.baidu.com/link?url=YEubSHRkbAgKHfP1MvL6ArNn-_mrsQRxGaRqY4Ey01EiEIblyGw5QNEfemEmrqQZw0X70Pkw9Ziqa52ShR4WGa
Implementation principle and application of atomic package in Java