Java multithreading atomic operation of / CAS based atomic and atomic

volatile

Introduction

Visibility problems
  • Let modify a thread to shared variables, other threads can be seen in time.
  • According to JMM specified happen before and synchronization principles:
    • Write to a volatile field Read operation happens-before every subsequent to the volatile field.
    • Write volatile variable v, synchronized with all other threads in the subsequent reading of the v
To avoid visibility problems, volatile functions need to have what
  1. Disable caching;
  2. volatile variable access control characters will add ACC _VOLATILE
  3. docs.oracle.com/javase/spec…
  4. Instruction is not related to volatile variables reordering;

Thread Safety

Critical region and race conditions

  1. Race conditions: critical region, triggering the code thread-safety issues.
  2. Critical zone: multiple threads, thread-regional security issues occur.

Share resource

  • If a piece of code is thread-safe, it does not include race conditions. Only when multiple threads updating shared resource, race conditions will occur.
  • When the stack is closed, will not be shared between the threads of the variables are thread safe.
  • Local object reference itself is not shared, but the referenced object is stored in the shared heap. If the object is created in the method, but the method of delivery, and other threads are not available, then also thread-safe.
public void someMethod(){
    Localobject localobject = new Localobject();
    localobject.callMethod();
    method2(localobject);
}
public void method2(Localobject localobject{
	localobject.setValue("value");
}
复制代码

Immutable objects

Create a shared object can not be changed to ensure that will not be modified when the object is shared between threads in order to achieve thread safety. Instance is created, value variables can no longer be changed, this is the immutability.

public class Demo{
    private int value = O;
    public Demo(int value){
    	this.value = value;
    }
    public int getValue(){
    	return this.value;
    }
}
复制代码

Atomic operation

Essence: data consistency

Atomic definition

  1. Effects of the atomic operation variables, with atomic operation, the consistency (or change can not occur can not be modified).

CAS mechanism

  1. Close to the direct operation of the memory

Unsafe using atomicity

  1. 取 unsafe.getIntVolatile
  2. change
  3. write
static{
    try{
        //反射技术拿到对象
        Field theUnsafe = Unsafe.class. getDeclaredField( name: "theUnsafe");
        theUnsafe.setAccessible(true);
        unsafe = (Unsafe)theUnsafe.get(null):
        //利用unsafe,通过属性的偏离量(定位到内存中对象内具体的属性的内存地址)
        iOffset = unsafe.objectFieldPffset(LockDemo1.class.getDeclaredField(name: "i")) :
    } catch (Exception ex) {
        ex.printStackTrace();
	}
}
//优化
public void add(){
    int current; 
    //i++;
    current = unsafe.getIntVolatile( o: this, iOffset);
    unsafe.compareAndSwapInt( o: this.iOffset, current, i1: current + 1):
    // CAS命令
}
复制代码
  • getIntVolatile attention to this volatile, banned instruction reordering and caching
  • All native modified native method
    • Non-native java method, implemented in C.
  • unsafe is the offset of the current object based on the variables, to obtain the current position in variable memory
  • Disadvantages: the case of high concurrency, and will continue to retry, resulting in resource depletion.

Atomic using atomicity

Principle: Spinlocks

// volatile int i = 0;
AtomicInteger i = new AtomicInteger(initialValue: 0) ;
public void add() {
    i.incrementAndGet():// i++
}
复制代码

Use LongAdder atomicity

since:JDK 1.8+

  • Big Data processing ideas >>> divide and rule
  • Each thread has an exclusive accumulator, when needed sum, and then take out the sum. Avoid retry (Atomic) or competition (sync).
  • Write for high and low reading scene

Several problems exist CAS

ABA problem

  • What
    • The failure of this operation really succeeded, resulting in no way reflect the changes in the data.
  • Why
    • Thread 1 and Thread 2 CAS simultaneously initiated request for the variable i. Under the right circumstances, a thread should fail (This assumes Thread 2 will fail)
    • But after the successful execution of the thread 1, thread 2 Thread 3 prior to the execution. I will be back to the thread 2
    • Thread 2 believes that the value of i is 1, is I want to find, so again the value of i becomes 2
  • How
    • Do not defined as a simple data basic data types

How to avoid

  • Use JUC class with a version number
  • Not only judgment values and results
  • Variable data will pass a version number is recorded
  • compare time will increase the contrast to the version number

Atomic operations package provides classes JUC

thought

Divide and rule

Click on a picture of statistics

  • Multiple servers to count separately, do not separately record
  • Summary server summary of all records

image.png


Copyright Notice

  • Author: ** eve stay
  • This link: ** www.yuque.com/diamond/ndv...
  • Copyright: ** This blog article unless otherwise specified, are used  CC BY-SA 4.0  license. Please indicate the source!
  • Starting dates: ** 2019-6-26 22:09:01

Guess you like

Origin juejin.im/post/5d1cf363f265da1bca51f70f