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 realize AtomicInteger in CAS Operation

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces how to achieve AtomicInteger in the CAS operation, the article is very detailed, has a certain reference value, interested friends must read it!

ABA problems occur during CAS operations.

That is, if the value of V first changes from A to B, and then from B to A

Then it is still considered that a change has taken place and the steps in the algorithm need to be reperformed.

There is a simple solution:

Instead of updating the value of a reference, update two values, including a reference and a version number

Even if the value changes from A to B, and then to A, the version number is different.

Public final int incrementAndGet () {for (;;) {int current = get (); int next = current + 1; if (compareAndSet (current, next)) return next }} / / the approach of this method is to get the current value attribute value first, / / then add 1 to value and assign it to a local next variable. / / however, both steps are not thread-safe, / / but there is an endless loop inside, and you keep doing compareAndSet operations until you succeed, / / that is, the root of the modification is in the compareAndSet method. The above of the compareAndSet () method is all the content of the article "how to implement AtomicInteger in CAS operation". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Internet Technology

Wechat

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

12
Report