Java High concurrency Programming: Atomic class __ Algorithm

Source: Internet
Author: User
Tags visibility
1. Concurrent Programming Concepts of Atomic

An operation cannot be split again, that is, an operation or multiple operations are either fully executed and the process of execution is not interrupted by any factor or executed. A classic example is the issue of bank account transfer.
Increment operator + +, is not an atomic operation, it is to read the old value first, and then write back the new value, including 2 operational visibility

Visibility means that when multiple threads access the same variable, a thread modifies the value of the variable, and other threads can immediately see the modified value. Order of

That is, the order in which the program executes is executed in the order of the Code. But instruction reordering can affect the correctness of concurrent execution of threads

To execute the concurrency program correctly, you must ensure atomicity, visibility, and orderliness. As long as one is not guaranteed, it can cause the program to run incorrectly. concurrency, parallelism, serial

Parallelism is a logical simultaneous occurrence of multiple programs running at the same time.
Concurrency is a physical occurrence, which means running multiple programs at a point in time. 2. Atomic Class

Java.util.concurrent.atomic Package: A small toolkit for atomic classes that supports thread-safe programming that unlocks on a single variable 2.1 if the same variable is to be accessed by multiple threads, you can use the class in that package Atomicboolean Atomicinteger Atomiclong atomicreference 2.2 atomicintegerarray: An integer 2.3 in an array of operations also provides classes that can be used for reflection operations in this package Atomicreferencefieldupdater Atomicintegerfieldupdater Atomiclongfieldupdater

They can provide access to the associated field types. 3. Atomic Boolean Atomicboolean

The Atomicboolean class provides us with a Boolean value that can be read and written in atomic form, and it also has some advanced atomic operations, such as Compareandset (). The Atomicboolean class is located in the Java.util.concurrent.atomic package, and the full class name is Java.util.concurrent.atomic.AtomicBoolean. The Atomicboolean described in this section is in the Java 8 version, not the Java 5 version it was first introduced to.

The design philosophy behind Atomicboolean is explained in the "Comparison and Exchange" section of my Java concurrency guide theme. Create a Atomicboolean

You can create a atomicboolean like this:

Atomicboolean Atomicboolean = new Atomicboolean ();  

The above example creates a new Atomicboolean with a default value of FALSE.

If you want to set an explicit initial value for the Atomicboolean instance, you can pass the initial value to the Atomicboolean constructor:

Atomicboolean Atomicboolean = new Atomicboolean (true);  
gets the value of the Atomicboolean

You can obtain a Atomicboolean value by using the Get () method. Examples are as follows:

Atomicboolean Atomicboolean = new Atomicboolean (true);  

Boolean value = Atomicboolean.get ();  

The value variable will be true after the above code executes. set the value of Atomicboolean

You can set a Atomicboolean value by using the Set () method. Examples are as follows:

Atomicboolean Atomicboolean = new Atomicboolean (true);  

Atomicboolean.set (FALSE);  

The Atomicboolean value is false after the above code executes. Exchange Atomicboolean Values

You can exchange the value of a Atomicboolean instance by Getandset () method. The Getandset () method returns Atomicboolean the current value and sets a new value for Atomicboolean. Examples are as follows:

Atomicboolean Atomicboolean = new Atomicboolean (true);  
Boolean oldValue = Atomicboolean.getandset (false);  

The value of the OldValue variable after execution of the above code is True,atomicboolean the instance will hold the value false. The code successfully swapped Atomicboolean current value ture to False. Compare and set the value of Atomicboolean

The Compareandset () method allows you to compare the current value of a atomicboolean with an expected value, and a new value will be set for Atomicboolean if the current values are equal to expectations. The Compareandset () method is atomic, so a single thread executes it at the same time. So the Compareandset () method can be used for a simple implementation of a lock-like synchronization.

The following is an example of a compareandset ():

Atomicboolean Atomicboolean = new Atomicboolean (true);  

Boolean expectedvalue = true;  
Boolean newvalue      = false;  

Boolean wasnewvalueset = Atomicboolean.compareandset (Expectedvalue, newvalue);  

This example compares the current value of Atomicboolean with the true value, and if it is equal, updates the value of Atomicboolean to false. 4. Atomic integral type Atomicinteger

The Atomicinteger class provides us with an int variable for atomic read and write operations, and it also contains a series of advanced atomic operations, such as Compareandset (). The Atomicinteger class is located in the Java.util.concurrent.atomic package, so its full class name is Java.util.concurrent.atomic.AtomicInteger. The atomicinteger described in this section is in the Java 8 version, not the Java 5 version it was first introduced to.

The design philosophy behind Atomicinteger is explained in the "Comparison and Exchange" section of my Java concurrency guide theme. Create a Atomicinteger

Create a atomicinteger example as follows:

Atomicinteger Atomicinteger = new Atomicinteger ();  

This example creates a atomicinteger with an initial value of 0.
If you want to create a atomicinteger with a given initial value, you can do this:

Atomicinteger Atomicinteger = new Atomicinteger (123);  

This example passes 123 as a parameter to the Atomicinteger constructor, which sets the initial value of the Atomicinteger instance to 123. gets the value of the Atomicinteger

You can use the Get () method to obtain the value of the Atomicinteger instance. Examples are as follows:

Atomicinteger Atomicinteger = new Atomicinteger (123);  
int thevalue = Atomicinteger.get ();  
set the value of Atomicinteger

You can reset the value of the Atomicinteger by using the Set () method. The following is an example of Atomicinteger.set ():

Atomicinteger Atomicinteger = new Atomicinteger (123);  
Atomicinteger.set (234);  

The above example creates a atomicinteger with an initial value of 123 and updates its value to 234 in the second row. Compare and set the value of Atomicinteger

The Atomicinteger class also passes an atomic compareandset () method. This method compares the current value of the Atomicinteger instance with the expected values and, if they are equal, sets a new value for the Atomicinteger instance. Atomicinteger.compareandset () code example:

Atomicinteger Atomicinteger = new Atomicinteger (123);  

int expectedvalue = 123;  
int newvalue      = 234;  
Atomicinteger.compareandset (Expectedvalue, newvalue);  

This example first creates a new Atomicinteger instance with an initial value of 123. The Atomicinteger is then compared to the expected value of 123, and if it is equal, the Atomicinteger is updated to 234. Increase Atomicinteger value

The Atomicinteger class contains methods by which you can increase the value of Atomicinteger and get its value. These methods are as follows: Addandget () Getandadd () getandincrement () Incrementandget ()

The first Addandget () method adds a value to the Atomicinteger and then returns the incremented value. The Getandadd () method adds a value to the Atomicinteger, but returns a value that increases the previous atomicinteger. Which one to use depends on your application scenario. The following are examples of the two methods:

Atomicinteger Atomicinteger = new Atomicinteger ();  
System.out.println (atomicinteger.getandadd);  
System.out.println (Atomicinteger.addandget (10));  

This example prints out 0 and 20. In the example, the second line gets the value of the Atomicinteger before adding 10. The value before adding 10 is 0. The third line Atomicinteger the value plus 10 and returns the value after the addition operation. The value is now 20.

You can of course use these two methods to add negative values to Atomicinteger. The result is actually a subtraction operation.

The Getandincrement () and Incrementandget () methods are similar to Getandadd () and Addandget (), but add only the Atomicinteger value by 1 at a time. reduce the value of Atomicinteger

The Atomicinteger class also provides some atomic methods for reducing the value of Atomicinteger. These methods are: Decrementandget () getanddecrement ()

Decrementandget () The value of the Atomicinteger is reduced by one and returns the value minus one. Getanddecrement () also cuts the value of the Atomicinteger by one, but it returns the value of minus one. 5. Atomic Long integer type Atomiclong

The Atomiclong class provides us with a long variable for atomic read and write operations, and it also contains a series of advanced atomic operations, such as the Compareandset () Atomiclong class located in Java.util.concurrent.atomic package, so its full class name is Java.util.concurrent.atomic.AtomicLong. The atomiclong described in this section is in the Java 8 version, not the Java 5 version it was first introduced to.

The design philosophy behind Atomiclong is explained in the "Comparison and Exchange" section of my Java concurrency guide theme.

Create a Atomiclong
Create a atomiclong as follows:

Atomiclong Atomiclong = new Atomiclong ();  

A atomiclong with an initial value of 0 will be created.
If you want to create a atomiclong that specifies the initial value, you can:

Atomiclong Atomiclong = new Atomiclong (123);  

This example passes 123 as a parameter to the Atomiclong constructor, which sets the initial value of the Atomiclong instance to 123.
Gets the value of the Atomiclong
You can get the value of the Atomiclong by getting the () method. Atomiclong.get () Example:

Atomiclong Atomiclong = new Atomiclong (123);  

Long thevalue = Atomiclong.get ();  

Set the value of Atomiclong
You can set the value of the Atomiclong instance through the set () method. An example of a atomiclong.set ():

Atomiclong Atomiclong = new Atomiclong (123);  

Atomiclong.set (234);  

This example creates a new Atomiclong with an initial value of 123, and the second row sets its value to 234. Compare and set the value of Atomiclong

The Atomiclong class also has an atomic compareandset () method. This method compares the current value of the Atomiclong instance with an expected value and, if two are equal, sets a new Atomiclong instance. Atomiclong.compareandset () using the example:

Atomiclong Atomiclong = new Atomiclong (123);  

Long expectedvalue = 123;  
Long NewValue      = 234;  
Atomiclong.compareandset (Expectedvalue, newvalue);  

This example creates a new Atomiclong with an initial value of 123. The current value of the Atomiclong is then compared to expected 123, and if it is equal, the new value of Atomiclong will change to 234. Increase Atomiclong value

Atomiclong has a number of ways to increase the value of Atomiclong and return its own value. These methods are as follows: Addandget () Getandadd () getandincrement () Incrementandget ()

The first method Addandget () adds a number to the Atomiclong value and returns the incremented value. The second method, Getandadd (), also adds a number to the Atomiclong value, but returns the value of the Atomiclong before it is incremented. Exactly which one you use depends on your own scene. Examples are as follows:

Atomiclong Atomiclong = new Atomiclong ();  
System.out.println (atomiclong.getandadd);  
System.out.println (Atomiclong.addandget (10));  

This example prints out 0 and 20. In the example, the second line gets the value of the Atomiclong before adding 10. The value before adding 10 is 0. The third line atomiclong the value plus 10 and returns the value after the addition operation. The value is now 20.

You can of course use these two methods to add negative values to Atomiclong. The result is actually a subtraction operation.

The Getandincrement () and Incrementandget () methods are similar to Getandadd () and Addandget (), but add only the Atomiclong value by 1 at a time. reduce the value of Atomiclong

The Atomiclong class also provides some atomic methods for reducing the value of Atomiclong. These methods are: Decrementandget () getanddecrement ()

Decrementandget () The value of the Atomiclong is reduced by one and returns the value minus one. Getanddecrement () also cuts the value of the Atomiclong by one, but it returns the value of minus one. 6. Atomic Reference type Atomicreference

Atomicreference provides an object reference variable that can be read and written by Atomicity. Atomicity means that multiple threads that want to change the same atomicreference do not cause atomicreference to be in an inconsistent state. Atomicreference also has a Compareandset () method by which you can compare the current reference to an expected value (reference) and, if it is equal, set a new reference inside the Atomicreference object. Create a atomicreference

Create Atomicreference as follows:

Atomicreference atomicreference = new Atomicreference ();  

If you need to create a atomicreference using a specified reference, you can:

String initialreference = "The initially referenced string";  
Atomicreference atomicreference = new Atomicreference (initialreference);  
Create generic Atomicreference

You can use Java generics to create a generic atomicreference. Example:

atomicreference<string> atomicstringreference =  
    new atomicreference<string> ();  

You can also set an initial value for the generic atomicreference. Example:

String initialreference = "The initially referenced string";  
atomicreference<string> atomicstringreference =  new atomicreference<string> (initialReference);  
Get atomicreference Reference

You can use the Atomicreference get () method to obtain a reference stored in atomicreference. If your atomicreference is Non-generic, the Get () method returns a reference of type Object. If it is generic, get () will return the type that you declared when you created the atomicreference.

Let's take a look at a non-generic atomicreference get () Example:

Atomicreference atomicreference = new Atomicreference ("A-referenced");  
String reference = (string) atomicreference.get ();  

Notice how the reference returned by the Get () method is cast to String.
Atomicreference Examples of generics:

atomicreference<string> atomicreference =   new Atomicreference<string> ("A-referenced");
String reference = Atomicreference.get ();  

The compiler knows the type of reference, so we no longer have to cast the reference returned by Get (). Set Atomicreference Reference

You can use the Get () method to set the reference that is saved inside the atomicreference. If you define a non-generic atomicreference,set () it will be an Object reference as an argument. If the generic Atomicreference,set () method will only accept the type you define.

Atomicreference Set () Example:

Atomicreference atomicreference = new Atomicreference ();  
Atomicreference.set ("New object referenced");  

This looks like non-generic and generics are no different. The real difference is that the compiler will limit the type of atomicreference parameter you can set to a generic type. Compare and set atomicreference references

The Atomicreference class has a very useful approach: Compareandset (). Compareandset () can compare the references stored in atomicreference to a desired reference, if two references are the same (not equals (), but = =), the Atomicreference instance to set a new reference.

If Compareandset () sets a new reference for Atomicreference, Compareandset () returns True. otherwise Compareandset () returns false.

Atomicreference Compareandset () Example:

String initialreference = "initial value referenced";  

atomicreference<string> atomicstringreference =  
    new atomicreference<string> (initialReference);  

String newreference = "new value referenced";  
Boolean exchanged = Atomicstringreference.compareandset (initialreference, newreference);  
System.out.println ("exchanged:" + exchanged);  

exchanged = Atomicstringreference.compareandset (initialreference, newreference);  
System.out.println ("exchanged:" + exchanged);  

This example creates a generic atomicreference with an initial reference. Comparesandset () is then invoked two times to compare the stored values to the expected value, and if the two are consistent, set a new reference for Atomicreference. For the first comparison, the stored reference (initialreference) is consistent with the expected reference (initialreference), so a new reference (Newreference) is set to Atomicreference, The Compareandset () method returns True. In the second comparison, the stored reference (newreference) is inconsistent with the expected reference (initialreference), so the new reference is not set to the Atomicreference,compareandset () method to return false.

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.