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

How to apply CAS of java

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use CAS of java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to use CAS of java".

CAS explained:

CAS (compare and swap), compare and exchange. A mechanism that can solve the performance loss caused by the use of locks in the case of multithread parallelism. The CAS operation consists of three operands-memory location (V), expected original value (A), and new value (B). If the value of the memory location matches the expected value, the processor automatically updates the location value to the new value. Otherwise, the processor does nothing. A thread gets the num value from the main memory and operates on the num. when writing in the value, the thread compares the numb value taken for the first time with the numb value in the main memory. If it is equal, it writes the changed num to the main memory. If it is not equal, it keeps looping until it is successful.

CAS produces:

The volatile keyword is often used when decorating shared variables, but the volatile value has visibility and forbids instruction replay (orderability), which cannot guarantee atomicity. Although there is no problem in single thread, there will be all kinds of problems in multi-thread, resulting in unsafe phenomenon on the spot. Therefore, after jdk1.5, CAS uses the CPU primitive (indivisible, continuous uninterrupted) to ensure the atomicity of the field operation.

CAS applications:

The addition of java.util.concurrent (JUC) in JDK1.5 is based on CAS. Compared with the locking mechanism of synchronized, CAS is a common implementation of non-blocking algorithm. So JUC has a great improvement in performance.

For example, the AtomicInteger class, AtomicInteger is thread-safe, here is the source code

Enter the unsafe to see the do while self-loop. The self-loop here determines that if the expected original value does not match the original value, it will recycle the original value and then go through the CAS process until the new value can be assigned successfully.

Advantages of CAS

Cas is an optimistic lock idea, and is a non-blocking lightweight optimistic lock, non-blocking refers to the failure or hang of one thread should not affect the failure or hang of other threads.

Shortcomings of CAS

The cycle time is long, the overhead is large, and it takes up CPU resources. If the spin lock is not successful for a long time, it will bring a lot of overhead to CPU. If JVM can support the pause instructions provided by the processor, then the efficiency will be improved to a certain extent. Pause instructions have two functions. First, it can delay pipelined execution of instructions (de-pipeline), so that CPU will not consume too much execution resources. The delay time depends on the specific version of the implementation. On some processors, the delay time is zero. Second, it can avoid the CPU pipeline being emptied (CPU pipeline flush) caused by memory sequence conflict (memory order violation) when exiting the loop, thus improving the execution efficiency of CPU.

Only one atomic operation of a shared variable is guaranteed. When performing operations on a shared variable, we can use cyclic CAS to guarantee atomic operations, but when operating on multiple shared variables, cyclic CAS cannot guarantee the atomicity of the operation, so locks can be used, or there is a trick to merge multiple shared variables into one shared variable to operate. For example, if you have two shared variables, iAccord2JazeA, merge ij=2a, and then use CAS to manipulate ij. Starting with Java1.5, JDK provides AtomicReference classes to ensure atomicity between reference objects, and you can CAS multiple variables in one object.

ABA problem

Solve the ABA problem (if the value considers the ending, you can ignore the modification problem without considering the process)

Add version number

AtomicStampedReference

Starting with Java1.5, a class AtomicStampedReference is provided in JDK's atomic package to solve ABA problems. The compareAndSet method of this class first checks whether the current reference is equal to the expected reference, and whether the current flag is equal to the expected flag, and if all are equal, atomically sets the reference and the value of the flag to the given update value.

Timing of CAS use

With a small number of threads and short waiting time, spin lock can be used for CAS to attempt to acquire lock, which is more efficient than synchronized.

The number of threads is large, the waiting time is long, spin lock is not recommended, and CPU is high.

At this point, I believe you have a deeper understanding of "how to use CAS of java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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