"Java Concurrent programming" deep analysis Atomicinteger (ii) __ algorithm

Source: Internet
Author: User

What is thread security
If a class can be safely used by multiple threads, it is thread-safe. You can't argue about this argument, but you can't get any more meaningful help from it. So how do we distinguish between thread-safe and non-thread-safe classes. How do we even understand "security"? The key to any reasonable thread safety definition is the concept of "correctness". In <>, the author defines this: A class is thread-safe, meaning that a class can continue to behave correctly when accessed by multiple threads.
Hint: the author of the book also wrote, as follows:
When multiple threads access a class, the class is called thread-safe if it does not take into account the scheduling and alternating execution of these threads in the run-time environment, and does not require additional synchronization and no other coordination of the caller's code, which is still the correct behavior.
Code Demo: Implementing a Counter
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
Package com.lll.test;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;
Import Java.util.concurrent.atomic.AtomicInteger;

public class Unsafecount {
public static Atomicinteger count = new Atomicinteger (0);
public static int count = 0;

public static Void Inc () {  
    try {  
        thread.sleep (1000);  
    } catch (Interruptedexception e) {  
        E.printstacktrace ();  
    }  
    Count.incrementandget ();  
    count++;  
}  

public static void Main (string[] args) throws interruptedexception {  

    Executorservice service= Executors.newfixedthreadpool (integer.max_value);  

    for (int i = 0; i < i++) {Service.execute (  
        new Runnable () {@Override public  
            void Run () {  
                Unsa Fecount.inc ();}}  
        );  

    Service.shutdown ();  
    Avoid the main main thread running first and the child thread is not finished, here to give a shutdown time  
    service.awaittermination (3000,timeunit.seconds);  
    SYSTEM.OUT.PRINTLN ("Run Result: unsafecount.count=" + unsafecount.count);  
}  

}

Tip: To improve the accuracy of the test, notice the 36th line Comment "Avoid the main main thread running first and the child thread is not finished, give a closing time here".
Run Result:
Run Result: unsafecount.count=92
Run Result: unsafecount.count=98
....
Based on the results, it can be seen that in a multithreaded environment, the expected correct result is not obtained 100.

Cause analysis
As we all know, the computer in the execution of the program, each instruction is executed in the CPU, and the execution of instructions in the process, it is bound to involve data reading and writing. Because the temporary data in the process of running the program is stored in the main memory, there is a problem, because the CPU execution speed, while the process of reading data from the main memory and writing to the main memory is faster than the CPU to execute instructions more slowly, Therefore, if the operation of the data at any time through the interaction with the main memory, will greatly reduce the speed of instruction execution. So there's the main memory and the local memory. That is, when the program is running, the data needed for the operation is copied from main memory to the thread's local RAM, and a copy of the count variable is created so that the CPU can load, use, assign, and write to memory directly from local memory, and then synchronize the replica values into main memory at the end of the calculation. The following figure:

Photo Excerpt from Http://images.cnblogs.com/cnblogs_com/aigongsi/201204/201204011757235219.jpg
However, these operations are not atomic, and when the line Cheng is synchronizing the new replica value to main memory, thread two comes in and loads from local memory to the old data before the thread is modified, which results in a different data than expected.

Solution One
Using Atomicinteger
A class that provides an integer for atomic operations. In the Java language, ++i and i++ operations are not thread-safe and will inevitably use the Synchronized keyword when used. and Atomicinteger through a thread-safe addition and subtraction operation interface. The code is as follows:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
Package com.lll.test;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;
Import Java.util.concurrent.atomic.AtomicInteger;

public class Unsafecount {
public static Atomicinteger count = new Atomicinteger (0);
public static int count = 0;

public static Void Inc () {  
    try {  
        thread.sleep (1000);  
    } catch (Interruptedexception e) {  
        E.printstacktrace ();  
    }  
    Count.incrementandget ();  
    count++;  
}  

public static void Main (string[] args) throws interruptedexception {  

    Executorservice service= Executors.newfixedthreadpool (integer.max_value);  

    for (int i = 0; i < i++) {Service.execute (  
        new Runnable () {@Override public  
            void Run () {  
                Unsa Fecount.inc ();}}  
        );  

    Service.shutdown ();  
    Avoid the main main thread running first and the child thread is not finished, here to give a shutdown time  
    service.awaittermination (3000,timeunit.seconds);  
    SYSTEM.OUT.PRINTLN ("Run Result: unsafecount.count=" + unsafecount.count);  
}  

}

Test results
Run Result: unsafecount.count=100
Atomicinteger Source Analysis

[Java] View plain copy on the code to see a piece of coding derived from my Code slice
Setup to use Unsafe.compareandswapint for updates
private static final Unsafe Unsafe = Unsafe.getunsafe ();
Private static final long valueoffset;

static {  
  try {  
    valueoffset = Unsafe.objectfieldoffset (AtomicInteger.class.getDeclaredField ("value"));  
  } catch (Exception ex) {throw new Error (ex);}  
}  

From the UML class diagram and code above, we can see that atomicinteger and unsafe are related. It obtains an instance of unsafe in the class, and then obtains the position of value in memory by the Objectfieldoffset method of the unsafe instance. Why it gets the position of value in memory. We analyze it from the Incrementandget method in turn
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
/**
* 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 to Next;
}
}
The first step is to obtain value +1 from the Get () method and pass it to the Compareandset method. The Compareandset code is as follows:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
Public final Boolean compareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect, update);
}
+ —————————————————————— +
"Atomically sets the value to the given updated value if the current value {@code = =} The expected value. @return True if Successful. False return indicates that the actual value is not equal to the expected value.
+ —————————————————————— +
Step Two: The Compareandset () method gets the original value and the value to be updated. With the comments on the code, we can see that if the Valueoffset position contains the same value as the expect value, the update Valueoffset position is updated and returns True, or False if it is not updated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.