08: atomicity of thread-safe operations

    Description Terms and conditions of competition too :( critical region is actually multi-threaded access to the same resources) 
        multiple threads access the same resources, have been written to these resources, and has requested execution order. On race conditions may occur. 
        Critical section: a piece of code, if in the case of multi-threaded execution, the results will have an impact. Then this code is the critical area. 
        Race conditions: it refers to the case of multi-threaded environment competition shared resources. 
    Atomic operations: 
        atomic operation is a step, or a plurality of steps, but the order of execution can not be disturbed, cutting can not be performed in part. (Uninterruptible) so that the entire operation is regarded as atoms. 
        The critical zone is converted into atomic operations. Guarantee thread safety. 
    CAS mechanism: 
        This is the underlying mechanism to achieve atomicity. 
        Compare and swap compare and swap, a hardware primitives, basic atomic memory operations provided by the processor 
        CAS operation requires two parameters (the old value and new value): old value and then compare the new updated value. 
        Whether changes to older values when in operation, if a change has occurred: another thread has already explained its modification, do not write the new value. 
                                          If not changed: Description This value does not change, you can write a new value. 
    JUC package wrapper classes provide atomic :( actually used) CAS mechanism implemented 
        AtomicBoolean: Boolean type atomic update 
        AtomicInteger: atomic update Integer
        AtomicLong: Long atomic update 
        , update the reference array there update, update field. 
        jdk1.8 updated: providing greater efficiency counter. Multi-threaded high efficiency, the scene for frequent updates but not frequently read. 
            Counter: DoubleAdder, LongAdder 
            updater: DoubleAccumulator, LongAccumulator. (Enhanced version of the counter, in addition to the added column, may also perform customized calculations) 
        , for example, implement an integer increment: 
         of AtomicInteger I = new new of AtomicInteger (0 );
          public  void the Add () {
              // underlying class using Unsafe.class achieve. This class can directly manipulate memory. CAS mechanism implemented, thus ensuring atomicity. Unsafe possible platforms, and unsafe. 
            i.incrementAndGet (); 
         } 
    disadvantage of CAS:
         1: + cycle CAS is a thread running at high frequencies, the waste of resources
         2: only for a single variable, the data can not simultaneously control a plurality of atoms.

 

Guess you like

Origin www.cnblogs.com/Xmingzi/p/12617367.html