Thread-safe -JUC

In a multithreaded development, the problems we often encounter is concurrent data, how to ensure the security thread, how to ensure that data is not repeated.

1. volatile

volatile is a java keyword, commonly used in shared variables in multiple threads

volatile principle

Each thread has its own thread storage space, and when the data storage space is synchronized to the main memory is uncertain.

volatile variables plus lock does not give, the better performance than synchronized, the thread all the time to read the data directly read memory (modify the value of a variable in the thread A volatile can guarantee that variable will be written back main memory, while the other thread will go to main memory to get the value of the variable)

volatile advantages and disadvantages

  • Thread concurrency to ensure the visibility of the variables (when this variable changes, is visible to other threads, the thread variable cache failure, the thread is always to get the latest modification of value)
  • volatile variables are not allowed inside the thread cache buffer and reordering to ensure the orderly
  • volatile only guarantee atomicity during each read or modify, i ++ does not guarantee atomicity (guaranteed only a single read / modify atomicity)

2. CAS (compare And Swap)

CAS can know by name, to compare the exchange value, after jdk1.5 been introduced, and by the old value memory comparison, the same word is modified to a new value

Compare And Swap原理

When the CAS instruction is executed only when the memory address and the time will change the value of the same value in memory changes to the value you want to modify, or directly return the latest value will not do anything, but will occasionally try again unless updated until the (spin). Because of this, CAS even if there is no lock, other threads can detect changes to the current variable.

CAS achieved by JNI (java local call), the use of unsafe operating atomicity (atomicity unsafe hardware level operating system, either succeed together or fail together)

The advantages and disadvantages Compare And Swap

advantage:

  • Genlock achieved without the aid of data sharing between threads (dependent variable exposure volatile)
  • From idea is, synchronized belong pessimistic locking, pessimistic concurrency considered serious, clung tightly resources; and CAS belong optimistic locking, concurrency optimistic that the situation is not very serious, and then compare the value of memory inconsistency will be repeated heavy test

Shortcoming

  • CPU overhead is relatively large, because of the spin mechanism of CAS, will lead to a thread repeated attempts to update a value, CPU brings a lot of pressure
  • Only guarantee atomicity of a variable can not be guaranteed atomicity code block
  • ABA problem
ABA举证:
场景:假设ATM机底层用CAS实现的存取钱操作
小明账户还有100元,在ATM机上准备取出50元,假如ATM机bug或者鼓掌,小明触发了2次取钱操作;
这个时候如果只是触发了2次也没关系,在第一个请求处理时,根据CAS原理,对比账户余额和实际账户余额是一致的都是100,此时账户剩余50,并发的第二次取钱操作根据原理肯定是不会执行,但是会阻塞等待重试;这个时候是对账户没有任何影响的。
再假设如果在小明取钱的同时,小明家里给小明打了50元钱;这个时候还会是这样的情况?
在打钱线程执行的时候,发现账户余额期望值50与账户一致,打钱成功,账户余额:100;这还没完,
第2次取钱操作此时重试,发现期望值100与余额一致,余额扣款成功;

小明的账户经历了: 100(A) --> 50(B) --> 100(A) --> 50

avatar

ABA解决方法:在比较期望值和内存值的时候在增加比对内存地址值的版本号是否一致,线程每次在变更内存地址值的时候都会刷新版本。可以通过AtomicStampedReference类来实现版本的比较

public boolean compareAndSet(V   expectedReference,
                                 V   newReference,
                                 int expectedStamp,
                                 int newStamp) {
        Pair<V> current = pair;
        return
            expectedReference == current.reference &&
            expectedStamp == current.stamp &&
            ((newReference == current.reference &&
              newStamp == current.stamp) ||
             casPair(current, Pair.of(newReference, newStamp)));
    }

CAS applications

In java.util.concurrent and contracting in

  • AQS (AbstractQueuedSynchronizer), and a series of blocking locks frame FIFO waiting queue, which are dependent on the underlying state variable atomicity operation done to achieve synchronization, there are used modified state CAS etc ...
protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }
  • AtomicInteger, AtomicBoolean so you can update the values ​​compareAndSet

In application development

  • Request may be achieved by concurrent operations based ato
  • By cas atomicity operation to a variable

Guess you like

Origin www.cnblogs.com/hetangyuese/p/11655398.html