Java thread (10): CAS, java thread cas

Source: Internet
Author: User

Java thread (10): CAS, java thread cas
Preface

In the Java concurrent package, there is such a package, java. util. concurrent. atomic, which is an atomic encapsulation of some Java data types. Based on the original data types, it provides atomic operation methods to ensure thread security. The following uses AtomicInteger as an example to illustrate how it is implemented.

public final int incrementAndGet() {    for (;;) {        int current = get();        int next = current + 1;        if (compareAndSet(current, next))            return next;    }}
public final int decrementAndGet() {    for (;;) {        int current = get();        int next = current - 1;        if (compareAndSet(current, next))            return next;    }}

Taking the two methods as an example, the incrementAndGet method is equivalent to the atomic ++ I, the decrementAndGet method is equivalent to atomic -- I (according to Chapter 1 and Chapter 2, we know that ++ I or -- I is not an atomic operation ), both methods do not use blocking methods to ensure atomicity (such as Synchronized). How do they ensure atomicity? CAS is introduced below.

Compare And Swap

CAS is a special command widely supported by modern CPUs to operate on shared data in memory. This command performs atomic read/write operations on the shared data in the memory. A Brief Introduction to the operation process of this command: first, the CPU will compare the data to be changed in the memory with the expected value. Then, when the two values are equal, the CPU will replace the value in the memory with the new value. Otherwise, no operation is performed. Finally, the CPU returns the old value. These operations are atomic. Although they seem complicated, they are the root of the Java 5 concurrency mechanism over the original lock mechanism. Simply put, CAS means "I think what the original value should be. If yes, it will update the original value to a new value; otherwise, it will not be modified, and tell me the original value ". (This description is taken from Java concurrent programming practices.)
In short, CAS has three operands, memory value V, old Expected Value A, and new value B to be modified.If and only when the expected value A and the memory value V are the same, change the memory value V to B. Otherwise, the system returns. This is an optimistic lock idea. It believes that there is no other thread to modify it before it is modified; and Synchronized is a pessimistic lock, which is considered before it is modified, there must be other threads to modify it, And the pessimistic lock efficiency is very low. Next, let's take a look at how AtomicInteger uses CAS to implement atomic operations.

Volatile variable
private volatile int value;
First, we declare a volatile variable value. In chapter 2, we know that volatile ensures the memory visibility of the variable, that is, the same value can be obtained at the same time in all work threads.
public final int get() {    return value;}
Compare And Set
// Setup to use Unsafe. compareAndSwapInt for updatesprivate static final Unsafe unsafe = Unsafe. getUnsafe (); private static final long valueOffset; // note that static {try {valueOffset = unsafe. objectFieldOffset (AtomicInteger. class. getDeclaredField ("value"); // returns the value Attribute and obtains its location in the memory.} catch (Exception ex) {throw new Error (ex );}} public final boolean compareAndSet (int exact CT, int update) {return unsafe. compareAndSwapInt (this, valueOffset, exact CT, update );}
Compare and set. Here we use the JNI method of the Unsafe class. Using the CAS command, we can ensure that read-Modify-write is an atomic operation. CompareAndSwapInt has four parameters: this-the current AtomicInteger object, the position of the Offset-value attribute in the memory (whether the value is in the memory must be emphasized), and the exact CT-expected value, update-new value. According to the above CAS operation process, when the value in memory is equal to the value in reverse CT, the value in memory is updated to the update value and true is returned. Otherwise, false is returned. Here, we need to have a simple understanding of Unsafe. In terms of name, it is not safe. Indeed, this class is a set of methods used to execute low-level and Unsafe operations, most of the methods in this class are direct operations on the memory, so it is not safe. However, when we use reflection and packet sending, Unsafe is indirectly used.

Loop settings

Now let's take a look at the two methods mentioned in the beginning. We will use incrementAndGet to analyze the implementation process.
Public final int incrementAndGet () {for (;) {// This is better than while (true) int current = get (); // get the current value int next = current + 1; // set the update value if (compareAndSet (current, next) return next ;}}
In the loop, obtain the current value and set the update value. Call compareAndSet to perform the CAS operation. If the operation is successful, the system returns the update to; otherwise, the retry ends until the operation is successful. There may be a hidden danger here, that is, the loop time is too long. When the current thread is compareAndSet, another thread sets the value (the idea is too bad), which is of course a small probability of time, currently, Java does not seem to be able to handle this situation.

Disadvantages

Although CAS can be used to implement non-blocking atomic operations, ABA problems may occur. We plan to take a separate chapter on ABA issues. (End) This article is from: Gao Shuang | Coder, original address: http://blog.csdn.net/ghsau/article/details/38471987,please note.

Java multithreading: How does one count every ten threads? Assume that the thread is used to sell tickets 1000, and a thread sells 200 to stop?

Check whether this is what you want.

Bytes -------------------------------------------------------------------------------------------
Public class ScoketTest {
Public static void main (String [] args) throws Exception {
For (int I = 1; I <= 10; I ++ ){
New Server (I + ""). start ();
}

}
}

Class Server extends Thread {

Private String name = null;
Private int count = 0;

Public Server (String name) throws Exception {
This. name = name;
}

Public void run (){
Try {
While (true ){
If (count = 200 ){
Break;
}
Count ++;
System. out. println ("thread" + name + ":" + count );
Int randeom = (int) (Math. random () * 100 );
Sleep (randeom );
}
System. out. println ("thread" + name + "stop! ");
} Catch (Exception e ){
}
}
}

If I create a Java thread, I keep it executed once every 10 minutes.

Import java. io. IOException;
Import java. util. Timer;

Public class TestAAA {

Public static void main (String [] args ){
Timer timer = new Timer ();
Timer. schedule (new MyTask (), System. currentTimeMillis ()-System. currentTimeMillis () % 600000 + 600000,600*1000); // execute this task for the next 10 minutes. The interval is 10 minutes. If you pass a Data parameter, you can execute this task at a fixed time.
While (true) {// This is used to stop this task, otherwise it will be executed cyclically.
Try {
Int ch = System. in. read ();
If (ch-'c' = 0 ){
Timer. cancel (); // use this method to exit the task

}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}

Static class MyTask extends java. util. TimerTask {

@ Override
Public void run (){
// TODO Auto-generated method stub
System. out. println ("task execution! ");
}
}
}

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.