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 atomic operation in web thread safety

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "what is the atomic operation in web thread safety". In the daily operation, I believe that many people have doubts about what the atomic operation in web thread safety is. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful to answer the doubt of "what is the atomic operation in web thread safety"! Next, please follow the editor to study!

Atomic operation

Atomicity means that the operation is indivisible. No matter it is multi-core or single-core, it has atomic quantity, and only one thread can operate on it at a time. An atomic operation can be a step or multiple steps, but the order cannot be disrupted or cut and only part of it (uninterruptible) can be performed. It is a core feature of atomicity that the operation is treated as a whole, and the resources are consistent in that operation.

First, let's look at an example of a non-atomic operation:

Public class Counter {volatile int i = 0; public void increament () {ionization;}}

Test the code:

Public class CouterTest {public static void main (String [] args) throws InterruptedException {final Counter counter = new Counter (); for (int I = 0; I < 6; iTunes +) {new Thread (new Runnable () {@ Override public void run () {for (int j = 0; j < 10000; junk +) {counter.increament () } System.out.println ("done...");}}) .start ();} Thread.sleep (6000L); System.out.println (counter.i);}}

Under correct circumstances, the above test code we started six threads each increased by 10000, the result output should be 60000, but the actual result is less than 60000, the reason is that iTunes + is not an atomic operation, through decompilation we can know that it is actually 4 instructions when JVM is running.

So how do you get the above code to run correctly?

In the form of locking, it can be synchronized locking or ReentrantLock locking. This way is to lock it into a serial single-threaded operation, the effect is not too high.

Example of syncchronized locking code:

Public class Counter {volatile int i = 0; public synchronized void increament () {ionization;}}

Example of ReentrantLock locking code:

Public class Counter {volatile int i = 0; Lock lock = new ReentrantLock (); public void increament () {lock.lock (); lock.unlock ();}}

AtomicInteger in the API of atomic operations provided by JDK, in which the underlying layer is through CAS operations or using multithreading, so it will be relatively efficient.

AtomicInteger code example:

Public class Counter {AtomicInteger I = new AtomicInteger (); public void increament () {i.incrementAndGet ();}} CAS (Compare and swap)

Compare and swap comparison and exchange are hardware synchronization primitives, and processors provide atomic guarantees for basic memory operations. The CAS operation contains 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 swaps the location value with the new value, and does not swap if it does not match, that is, if the value of the memory location changes. The sun.misc.Unsafe class in Java provides several methods to implement CAS, such as compareAndSwapInt and compareAndSwapLong. The code example is as follows:

/ / the atomic operation API provided by JDK basically works like this: public class CounterUnsafe {volatile int i = 0; private static Unsafe unsafe = null; / / I field address offset private static long valueOffset; static {/ / unsafe = Unsafe.getUnsafe (); this method is not available try {Field field = Unsafe.class.getDeclaredField ("theUnsafe"); field.setAccessible (true); unsafe = (Unsafe) field.get (null) Field fieldi = CounterUnsafe.class.getDeclaredField ("I"); / / get the address offset of field I valueOffset = unsafe.objectFieldOffset (fieldi);} catch (NoSuchFieldException | IllegalAccessException e) {e.printStackTrace ();}} public void increament () {for (;;) {int current = unsafe.getIntVolatile (this, valueOffset) / / if you succeed, return true, jump out of the loop, and if you fail to return false, you will spin (that is, for loop) if (unsafe.compareAndSwapInt (this, valueOffset, current, current + 1)) break;}. This ends the study of "what is the atomic operation in web thread safety". I hope you can 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: 292

*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