high concurrency java knowledge learning summary (a)

Concurrent: simultaneously has two or more threads, if the program is run on a single core processor, a plurality of alternating threads swapped or paged out, the threads are simultaneously present, each thread of execution in a states, when running on a multicore processor, this time, each thread in the program will be assigned to a processor core, can be run simultaneously.

 Why cpu cache: cpu frequency is too fast, approaching the main memory can not keep up, so always within the processor cycle, CPU is often need to wait for main memory, a waste of resources. So too cache appears to ease the speed mismatch between the CPU and memory problems.
  CPU cache What is the significance:
   1) temporal locality: If a data is accessed, then in the near future it could be accessed again
   2) spatial locality: If a data access is so, then with his neighbor data blocks may be quickly accessed
  CPU multi-level caches - cache coherence (MESI-- cache protocol)
  is used to ensure cache coherent shared data among a plurality of CPU cache
 
CPU multi-level cache - optimization of-order execution
 processor to increase operating speed and make optimized contrary to the code of the original order of
 
java memory model specifications (java memory model, JMM)
 is defined: java memory model specification defines how and when they can see a thread modified by other threads through shared variables values, and how to access shared variables must be synchronized in time.

  java heap memory: the memory can be allocated dynamically at run-time operation, and therefore the operation efficiency is relatively slower.
  java in the stack: advantages: access speed faster than java heap of access in faster data stack can be shared, but the stack size and survival data are determined. The main stack to store some basic data variables.
  Typically, when the cpu main memory to be read, will first read the data in the main memory into the cache, the cache will be read even some data to the internal registers,
  perform some in the register operating.
  java memory model - eight kinds of synchronous operation
  lock (lock): the role of main memory variable, the variable is identified as a state monopoly threads
  unlock (unlock): variable acting on the main memory variables, a locked state is released out before they can be used by other threads after release.
  read (read): variable acting on the main memory, transmitted to a variable from main memory into the working memory of the thread, for subsequent use load operation.
  load (load): the role of working memory variable, he read operation variable obtained from the main memory to the copy of the variable values into the working memory.
  use (use): the role of working memory variables, a variable working memory value is passed to the execution engine
  assign (assignment): the role of working memory variables, an assignment he received from the value of the execution engine to working memory Variables.
  store (store): the role of working memory variables, the value of a variable transmission in the working memory to main memory, for subsequent write operations
  write (writing): acting on the main memory variable, which the store operation transferred from the work memory to the value of a variable in main memory variable.
 
java memory model - synchronization rules
  if we want to copy a variable from main memory into the working memory, you need to perform read and load in the order, if the variable is synchronized back to the working memory from memory, you must follow the order of implementation of store and write operations. But java memory model requires only the above-described operation must be performed in sequence, but is not guaranteed to be executed continuously.
  Read and load, store and write operations allowed one alone
  does not allow a thread to discard its most recent assign the operation, ie, after variable changes in the working memory must be synchronized to the main memory.
   It does not allow a thread is no reason (not assign any action occurs) to synchronize data from your memory back to main memory in
   a new variable can only be born in the main memory, is not allowed to be used directly in a working memory has not been initialized ( load or assign) variables. That is, before the implementation of a variable use and store operations must be performed after a load operation and assign
   a variable at the same time allowing only one thread to perform the operation of its lock, but the lock operation can be repeated multiple times in the same thread, many times after performing lock, unlock operation only perform the same number of variables was only unlocked. lock and unlock must appear in pairs.
   If you do lock operation on a variable, will clear the working memory value of this variable, we need to re-execute the load and assign the value of variable initialization operation prior to the execution engine to use this variable.
  If a variable not previously been locked lock operation, it does not allow him to unlock the operation, do not allow unlock a locked by another thread of variable
 
  thread safety:
   atomicity: provides exclusive access, only one thread at a time him to operate
   visibility: modifications to the main memory of a thread can be observed in time to other threads
   orderly: observation of a thread other threads to execute instructions in sequence, since there is an instruction reordering, the general observation clutter disorderly
 
   CAS underlying thread-safe principle: the use of compareAndSwapInt methods, continue to use the current value of the underlying value is compared to main memory only when want to hear that when we come to be returned.
   actomicXXX categories: ensure the security thread. ,
   JDK1.8: the role of LongAdder class action and atomicLong class is the same.
   LongAdder class action: the separation of a hot main data, is treated separately.
   In the low-concurrent time, performance and atomicLong performance is the same, but when high concurrency, by dispersing improves the performance, but at the statistics, if there is concurrent updates can lead to statistical error.
   The need to generate an accurate value, globally unique value of time, atomicLong is the only choice.
   
   AtomicReference, AtomicReferenceFieldUpdate:
   AtomicReference:
 
   AtomicStampReference: CAS ABA problem if the data is modified to a modified A and B is further modified to A, version of the data will change
     
    atomic lock:
    the synchronized: the JVM-dependent (action role object the same time, only the range of an object to manipulate)
    Lock: dependent special CPU instructions, code implementation, of ReentrantLock  
   
    the synchronized:
    a modified code block: code braces, acting on the object call
    modification methods: the overall process, acting on the called object
    modification static methods: whole static method, applied to all objects
    modified class: bracketed portion, acting on all objects
    synchronized: synchronized method is not part of the method definition, so when synchronized modification methods are inherited when a subclass is not synchronized function.

    Visibility: visible not cause shared variables among threads:
     Thread interleaved execution  
     reordering binding cross thread execution
    value after update a shared variable is not updated in time between the working memory and the main memory
    
   JMM synchronized on two states:
    Thread unlock the front, the latest value of the shared variable must be flushed to memory.
    Thread lock, will clear the working memory shared values of variables in order to use the need to re-read from the main memory shared memory
   
     volatile: be achieved by adding a memory barrier and prohibit reordering optimization
     when volatile variable write operation will Add a store barrier instruction of the write operation, the local memory shared variable values flushed to main memory
     when volatile variables read, will add a load barrier instruction before a read operation, reading the shared variable from main memory
      
    volatile no atomicity comprising:
    applicable scenarios: 1, do not wrong variable dependent on the current value of
     2, the variable is not included in the other variables constant in real time
    is very suitable for variable state flag
    
 java memory model, allows the compiler and processor instructions to be reordered, but the reordering process will not affect the implementation of single-threaded, but it will affect the concurrent execution of multiple threads correctness
    volatile, synchtroniezed, lock
 
   Program sequence rule: within a thread, according to the order of the code book EDITORIAL current operations take place in writing at a later operation
   Blocking rule: a face unlock operation lock operation with a lock after the first occurrence in
   volatile variable rules: for a variable the first occurred after the write operation in the face of this variable read
    transfer rule: if a first operation occurred in the operation of B, and B and the operation occurred in the first operation C, the operation can be drawn a first operation occurred in the C
     thread start rule : start thread object () method first occurrence in this thread every action
     thread interrupts: call the thread interrupt () method first occurred in the interrupted thread code detection to interrupt the event
      thread terminates rules: All threads the operations are the first to occur of the termination detection thread, we can Thread.join () method ends, Thread.isAlive () return value means detects that the thread has terminated execution
     object finalization rule: an object initialization completion will occur first at the start of his finalized () method of the
     
 
     Object publishing:
   
     publishing objects Make an object to be outside the current extent of the code used by
     the object from escaping: a false release. When an object has not yet been constructed, it makes him seen by other threads.

     Display object escape code example:

 

MyStudyTest Package Penalty for; 

/ * * 
 * Whether to display a reference or implicit references will cause this escape, because the constructor has not been initialized, the other threads to see the value of the member variable 
 * Cause: object also not previously completed its initialization release constructor 
 * / 
public  class Example2 {
   Private  int thisCanBeEscape = 0 ; 

  public Example2 () { 

      new new InnerClass (); 
  } 

  Private  class InnerClass { 

      public InnerClass () { 
          . the System OUT .println ( " { } " . + Example2 the this .thisCanBeEscape); 
        } 

    }

 

If an object is a variable object, you need to be safe release, otherwise it will cause unsafe thread.

 Four ways to secure release objects:

 1, initialization of an object in a static initialization function references

 2, the reference object to save or volatile AtomicReference object type field.

3, saving a reference to an object is properly constructed final type of objects in the domain

4, saving a reference to a lock-protected objects in the domain

 

volatile keyword has two usage scenarios: 

   1, the state can do to identify the amount (because the keyword will work to refresh the data memory space in main memory)

    2, can detect double (keyword may be limited because the instruction register rearrangement occurs - double detection mechanism for single-mode idler embodiment)

 

MyStudyTest Package; 

/ * * 
 * lazy mode: 
 * the singleton instance created the first time the use of 
 * thread-safe, only suitable for use in the case where a single thread 
 * / 
public  class SingleTenExample {
     // private constructor, only when the private constructor type, it will not be easily created by other references out 
    private SingleTenExample () {}; 

    // singleton 
    private   static  volatile SingleTenExample instance = null ;
    // static factory method 
   / * public static SingleTenExample the getInstance () { 
        IF (instance == null) { 
            return new new SingleTenExample (); 
        }} * / 

    // add synchronized keyword to ensure thread safety 
       / *Synchronized SingleTenExample the getInstance static public () { 
            IF (instance == null) { 
               instance SingleTenExample new new = (); 
            } 
            } * / 

      // the above method, although to achieve the security thread, but inferior in terms of performance
      // double synchronization lock singleton
     // this way remains thread safe
     // memory registers complete instructions sequentially:
     // . 1, the allocate memory space = memory () assignment of
     // 2, ctorInstance () to initialize the object
     // 3, instance = memory set point just allocated memory instance 

    // the JVM and cpu optimization, reordering the instruction occurs 

    // . 1, the allocate memory space = memory () assignment of
     // . 3, instance = memory set point just assigned memory instance
     //2, ctorInstance () to initialize the object
     //
 
    / * * 
     * double detection mechanism need not be thread safe, is due to having instructions rearrangements may occur, 
     * when there are two threads calling getinstance method when thread A if just to perform instance = new SingleTenExample (), 2 and 3 occurred in the instruction sequence exchange, 
     * then thread B when the request instance == null, it will default instance has been created, return instance, the fact that the thread has not initialized, will lead thread safe 
     * 
     * Note: instructions occur can be limited by rearrangement volatile keyword 
     * / 

    public  static SingleTenExample the getInstance () {
         IF (instance == null ) { // double detection mechanism         // B 
            the synchronized (SingleTenExample. class ) { // synchronization lock 
                IF (instance == null) {
                    instance = new SingleTenExample(); // A - 3
                }
            }
        }
        return instance;
    }



}

 

Note: static fields and static code execution order is not the same paragraph, the result would have been different

Use enumeration to achieve Singleton pattern, but also a very safe singleton

package com.mmall.concurrency.example.singleton;

import com.mmall.concurrency.annoations.Recommend;
import com.mmall.concurrency.annoations.ThreadSafe;

/**
 * 枚举模式:最安全
 */
@ThreadSafe
@Recommend
public class SingletonExample7 {

    // 私有构造函数
    private SingletonExample7() {

    }

    public static SingletonExample7 getInstance() {
        return Singleton.INSTANCE.getInstance();
    }

    private enum Singleton {
        INSTANCE;

        private SingletonExample7 singleton;

        //This method is absolutely guaranteed JVM called only once 
        the Singleton () { 
            Singleton = new new SingletonExample7 (); 
        } 

        public SingletonExample7 the getInstance () {
             return Singleton; 
        } 
    } 
}

Why is the safest for the enumeration of detailed blog: https://www.cnblogs.com/wcgstudy/p/11408495.html

 

Immutable objects:

    Immutable object condition to be satisfied:

     1, after the object is created, its status can not be modified

      2, all fields are final target type

      3, when the object is created correctly (during object creation, this refers not escape)

final: it can be used to modify classes, objects, methods

     Modified class can not be inherited, all methods are final modified class is implicitly designated as the final method

     Modified: 1, locking methods are not inherited class Amendment 2, the efficiency (in the earlier versions of JDK method as a built-in way to improve efficiency, but when the method is too large, the efficiency will not be promoted)

                        2, private modification method will be converted implicitly to a modified method of final

 

    Variable modifications: 1, 2 basic variable data types, data type variable references (after being initialized, the object can not point to another)

                       When the final modification of the map, but reference to an object point to another is not allowed, but the value of which is to allow changes.

       java other methods of immutable objects stated: 

       1、 Collections.unmodifiableXXX:Collection、list、set、Map 

       2、 Guava : ImmutableXXX: Collection、list、set、Map 

       Data container is a modified method of the above two immutable 

       Code shows an example: 

      

package com.mmall.concurrency.example.immutable;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.mmall.concurrency.annoations.ThreadSafe;

@ThreadSafe
public class ImmutableExample3 {

    private final static ImmutableList<Integer> list = ImmutableList.of(1, 2, 3);

    private final static ImmutableSet set = ImmutableSet.copyOf(list);

    private final static ImmutableMap<Integer, Integer> map = ImmutableMap.of(1, 2, 3, 4);

    private final static ImmutableMap<Integer, Integer> map2 = ImmutableMap.<Integer, Integer>builder()
            .put(1, 2).put(3, 4).put(5, 6).build();


    public static void main(String[] args) {
        System.out.println(map2.get(3));
    }
}

 

         Thread closed: The package is subject to a thread, even if the existence of such objects is not thread-safe, there will not be thread-safe issue

        Implementing Threads closed in several ways:

       1, AD-HOC thread closed: program control is realized, the worst can be ignored

       2, the stack is closed: use local variables, no concurrency issues

       3, ThreadLocal closure threads: Thread particularly preferred method of closing, ThreadLocal bottom Map implementation uses a closed thread

     

       

        

 

 

 

 

      

 

 


      




   
   
   
 

Guess you like

Origin www.cnblogs.com/wcgstudy/p/11504147.html