Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Java atomic class

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is the Java atomic class". In the daily operation, I believe that many people have doubts about what is the Java atomic class. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the Java atomic class"! Next, please follow the editor to study!

The atomic classes in Java are objects under the java.util.concurrent.atomic package. The reason why they have atomic commonness comes from CAS, which shows the importance of CAS. There is no concurrency problem in the operation of atomic variables, and there is no need to use synchronization means to control concurrency. Its underlying implementation can ensure the visibility of variables and the atomicity of operations. Generally, we can use AtomicInteger,AtomicLong to achieve counters and other functions, and AtomicBoolean to achieve flag bits and other functions.

Atomic classes are provided by JDK5, there were only 12 atomic classes at that time, when it developed to JDK8, there were 4 more atomic classes, as shown in figure 2-25 below, the red box is newly added to JDK8.

Figure 2-25 Java16 atomic classes

Let's classify and explain these atomic classes.

2.10.1 basic types of atomic updates

L AtomicBoolean: atomic update Boolean type.

L AtomicInteger: atomic update integer.

L AtomicLong: atomic update long integer.

Let's take AtomicInteger as an example. The common methods of AtomicIngeter are as follows:

N int addAndGet (int delta): adds the parameter to the value in the instance in an atomic way and returns the result.

N boolean compareAndSet (int expect, int update): if the value entered is equal to the expected value, the value is set to the value entered atomically.

N int getAndIncrement (): increments the current value by 1 in an atomic way, and then returns the pre-incremented value, the old value. This method is also a commonly used method, which can be used to do counters.

N void lazySet (int newValue): will eventually be set to newValue, and setting the value with lazySet may cause other threads to read the old value for a short period of time.

N int getAndSet (int newValue): sets it to newValue atomically and returns the old value.

N int incrementAndGet (): like getAndIncrement, he returns the value since it was incremented.

Remember that in the code case that explains the CAS application, we have used the atomic self-increment method. Let's take a look at how getAndIncrement () implements the atomic operation. Please see the AtomicInteger part of the source code in the 2-45 sample code.

Listing 2-45 AtomicInteger.java

Public final int getAndIncrement () {return unsafe.getAndAddInt (this, valueOffset, 1);} public final int getAndAddInt (Object var1, long var2, int var4) {int var5; do {var5 = this.getIntVolatile (var1, var2);} while (! this.compareAndSwapInt (var1, var2, var5, var5 + var4); return var5;}

We get the old value, then pass the data to be added, call getAndAddInt () for atomic update operation, the actual core method is compareAndSwapInt (), using CAS for update. Our Unsafe only provides 3 CAS operations, and note that AtomicBoolean converts Boolean to an integer and operates using compareAndSwapInt. The objects in the atomic package are basically implemented using the methods of the CAS operation in 3 provided by Unsafe. Take a look at the Unsafe source code, as shown in listing 2-46.

Listing 2-46 Unsafe.java

/ * if the current value is var4, the atomic will update the java variable to var5 or var6 * @ return if the update succeeds and returns true * / public final native boolean compareAndSwapObject (Object var1, long var2, Object var4, Object var5); public final native boolean compareAndSwapInt (Object var1, long var2, int var4, int var5); public final native boolean compareAndSwapLong (Object var1, long var2, long var4, long var6)

2.10.2 Atomic Update Array

L AtomicIntegerArray: the atom updates the elements in the integer array.

L AtomicLongArray: the atom updates the elements in the long integer array.

L AtomicReferenceArray: atomic update references elements in an array of types.

The most common methods of these three classes are the following two:

N get (int index): gets the element value with an index of index.

N compareAndSet (int I, int expect, int update): if the current value is equal to the expected value, the element of the array position I is set to the update value atomically.

2.10.3 Atomic update reference type

L AtomicReference: atomic update reference type.

L AtomicReferenceFieldUpdater: the field of the atomic update reference type.

L AtomicMarkableReferce: the atom updates the reference type with tag bits, and you can update the tag bit and reference type of a Boolean type using the constructor.

The methods provided by these three classes are similar, first construct a reference object, then set the reference object into the Atomic class, and then call some methods such as compareAndSet to carry out atomic operations, the principle is based on Unsafe, but AtomicReferenceFieldUpdater is slightly different, updated fields must be decorated with volatile. Let's write a simple Demo using the atomic reference type, as shown in sample code 2-47

Listing 2-47 AtomicReferenceDemo.java

Public class AtomicReferenceDemo {public static AtomicReference ai = new AtomicReference (); public static void main (String [] args) {User U1 = new User ("pangHu", 18); ai.set (U1); User U2 = new User ("pangPang", 15); ai.compareAndSet (U1, U2); System.out.println (ai.get (). GetAge () + ai.get (). GetName ()) } static class User {private String name; private int age; / / omit getter, settrt}}

Output the results.

15pangPang

2.10.4 Atomic update field class

If you need to update a field in the atomic update class, you need to use the atomic update field class. The Atomic package provides three classes for atomic field update:

L AtomicIntegerFieldUpdater: an updater for fields of atomic update integers.

L AtomicLongFieldUpdater: an updater for atomic update long integer fields.

L AtomicStampedFieldUpdater: atomic update of reference types with version numbers. This method is more important, he and the reference type add an integer value to control the version number of the data, so that it can solve the ABA problem that may occur when CAS is updated. Fields that update a class like a reference type must be decorated with public volatile.

2.10.5 introduction to the new atomic class in JDK8

L DoubleAccumulator

L LongAccumulator

L DoubleAdder

L LongAdder

Let's take LongAdder as an example and list the points for attention.

These classes correspond to improvements to classes such as AtomicLong. For example, LongAccumulator and LongAdder are more efficient than AtomicLong in high concurrency environments.

The performance of Atomic and Adder is very similar in low concurrency environment. But in the high concurrency environment, Adder has significantly higher throughput, but higher space complexity.

LongAdder is actually a special case of LongAccumulator, and calling LongAdder is quite similar to calling LongAccumulator in the following way.

The sum () method is called without concurrency. If it is used in the case of concurrency, there will be a count error. Here is an example of the code below.

LongAdder cannot replace AtomicLong. Although the add () method of LongAdder can be operated atomically, it does not use Unsafe's CAS algorithm, but only uses the idea of CAS.

LongAdder is actually a special case of LongAccumulator. Calling LongAdder provides a more powerful function than LongAdder by calling LongAccumulator,LongAccumulator in the following way. In the constructor, accumulatorFunction, a binocular operator interface, returns a calculated value based on the two input parameters, and identity is the initial value of the LongAccumulator accumulator.

At this point, the study of "what is the Java atomic class" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report