Java Concurrency and high concurrency solutions - security release objects

Copyright: https://blog.csdn.net/qq_40722284/article/details/85098818

table of Contents

Publishing Objects

 Object escape

Object security release

Four ways

Lazy Mode - Example singleton

  Lazy mode -> Double synchronization lock singleton

Starving Mode - Example singleton

 Starving Mode - static code block instance singleton

 Enumeration way - singleton instance (the most secure, recommended)

Immutable objects

final keyword

Benefits final keyword

final knowledge summary


Publishing Objects

So that an object can be used by code outside of the current range

private String [] states = {"a", "b", "c"};

......

public static void main(String[] args) {

     a = new UnsafePushlish();

     log.info ( "before outputting the modification information"); // result is a, b, c

    a.getSates()[0] = "d";

     log.info ( "post-modification information output"); // result is d, b, c

}

 Object escape

A false release. When an object has not yet been constructed, it will be seen by other threads. (You can start () method the same start)

SLF4J @
@NotThreadSafe
@NotRecommend
public class the Escape {
    Private thisCanBeEscape int = 0;
    public the Escape () {
        new new InnerClass ();
    }
    Private inner class class InnerClass {//
        public InnerClass () {
            log.info ( "{}", the Escape . the this .thisCanBeEscape); // configuration when not fully been released, can already see this ------ this has overflowed
        }
    }
    public static void main (String [] args) {
        new new the Escape ();
    }
}

Object security release

Four ways

  1. In the static initialization function to initialize an object reference
  2. The object reference type field stored to volatile or subject AtomicReference
  3. The object reference saved to a properly constructed object type field final
  4. The object reference is saved to a domain protected by a lock

Lazy Mode - Example singleton

/**
 * 懒汉模式
 * 单例实例在第一次使用时进行创建
 */
public class SingletonExample1 {
    // 私有构造函数
    private SingletonExample1() {
    }
 
    // 单例对象
    private static SingletonExample1 instance = null;
    // 静态的工厂方法(在多线程时候,可以通过加synchronized使其同步) 但是在方法上加synchronized会增大性能消耗
    public static SingletonExample1 getInstance() {
        if (instance == null) {
            instance = new SingletonExample1();
        }
        return instance;
    }

  Lazy mode -> Double synchronization lock singleton

 / **
 * lazy Mode - "double synchronization lock Singleton
 * singleton instance created when first use
 * /
// thread-safe
public class SingletonExample4 {
    // private constructor
    Private SingletonExample4 () {
    }
    // instance = new SingletonExample4 (); operations occur


    Memory // 1, memory = allocate () assignment of
    // 2, ctorInstance () to initialize the object
    // 3, instance = memory disposed instance point just allocated memory
 
    // JVM and cpu optimization, reordering the instruction occurs
 
    / / 1, memory = allocate () allocated memory space object
    // 3, instance = memory disposed instance point just allocated memory
    // 2, ctorInstance () to initialize the object
 
    // singleton object
    Private static instance SingletonExample4 = null;
 
    // static factory method
    public static SingletonExample4 the getInstance () {
        IF (instance == null) {// // thread double detection mechanism B
            the synchronized (SingletonExample4.class) {// synchronization lock
                IF (instance == null) {
                    instance new new = SingletonExample4 (); // thread A -. 3
                }
            }
        }

        return instance;
    }

}

Thread safe - command rearrangement

ways to improve:

// singleton object double detection mechanism volatile + -> prohibition instruction reordering

Private volatile static SingletonExample5 instance = null; // thread-safe

Starving Mode - Example singleton

/ **
 * starving mode
 * singleton instance created when the class is loaded
 * /
public class SingletonExample2 {
    // private constructor
    Private SingletonExample2 () {
    }
    // singleton object
    Private static SingletonExample2 new new instance SingletonExample2 = ();
    / / static factory method
    public static SingletonExample2 the getInstance () {
        return instance;
    }
}

 Hungry man is thread-safe mode of operation, but if there are too many processed inside the constructor, it is to make class loading is very slow, affecting performance. And if it is loaded, but they did not use, a waste of resources

 Starving Mode - static code block instance singleton

 
/ **
 * starving mode
 * singleton instance created when the class is loaded
 * /
@ThreadSafe
public class SingletonExample6 {
    // private constructor
    Private SingletonExample6 () {
    }
    // singleton object
    Private static instance SingletonExample6 = null;   // . 1
    static {
        instance SingletonExample6 new new = (); // 2
    }

    // static factory method
    public static SingletonExample6 the getInstance () {      //. 3
        return instance;
    }
    public static void main (String [] args) {
        System.out.println (the getInstance () the hashCode ().);
        System.out.println (the getInstance () the hashCode ().);
    }
}

 The code sequence must be noted that the code blocks are executed in the order, order transposing Examples 1 and 2 is empty phenomenon occurs.

 Enumeration way - singleton instance (the most secure, recommended)

/ **
 * enumeration mode: safest
 * /
@ThreadSafe
@Recommend
public class SingletonExample7 {
    // private constructor
    Private SingletonExample7 () {
    }
    public static SingletonExample7 the getInstance () {
        return Singleton.INSTANCE.getInstance ();
    }

   Private enum {singleton
        INSTANCE;
        Private SingletonExample7 Singleton;
        // the JVM absolute guarantee that this method is called only once
        singleton () {
            Singleton new new SingletonExample7 = ();
        }
        public SingletonExample7 the getInstance () {
            return Singleton;
        }

    }
}

Relatively lazy mode, the thread safer

Relative starving mode, it is initialized when you call, saving resources 

Immutable objects

Immutable object condition to be satisfied:

  1. After the object is created that the state 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)

 Examples immutable objects

Collections.unmodifiableXXX:Collection、List、Set、Map....

= the Collections the Map. unmodifiableMap (the Map) ; // the Map can not be changed after modification, will throw an exception

Source Analysis: Returns a new unmodifiableMap (map), the value before copying the initialization after unmodifiableMap (map), the process needs to be updated to directly replace thrown.

Guava:ImmutableXXX:Collection、List、Set、Map.....

final keyword

May be modified classes, methods, variables

Modified class: can not be inherited, Java has many class is final, such as String, Interger and other packaging

Modification methods: 1, inherited type locking method is not modified; 2, efficiency

Variable modifications: basic data type variable, a reference type variable (not point to further variables after initialization), the value of the value set key / value may be varied in

Benefits final keyword

  1. final keyword improved performance. JVM and Java applications are cached final variable.
  2. final variables can safely be shared in a multithreaded environment, without the need for additional synchronization overhead.
  3. The final keyword, JVM will method, class variables and optimization.

final knowledge summary

  1. The final keyword can be used for member variables, local variables, methods and classes.
  2. final member variables must be initialized when they are declared or initialized in the constructor, otherwise it will report compilation errors.
  3. You can not assign a variable final again.
  4. Local variables must be assigned at the time of declaration.
  5. In the anonymous class in all variables must be final variable.
  6. final methods can not be overridden.
  7. final class can not be inherited.
  8. Unlike the final keyword finally keyword, which is used for exception handling.
  9. readily final keyword () method confused with finalize, the latter method is defined in the Object class, before the garbage collection method is called JVM.
  10. All variables declared in the interface itself is final.
  11. final and abstract both keywords are inversely related, final class can not be abstract of.
  12. final method at compile time binding, static binding (static binding).
  13. Uninitialized variable called final blank final variable (blank final variable) in the statement, they must be initialized in the constructor, or by calling this () to initialize. Do not do so, the compiler will complain "final variable (variable name) needs to be initialized."
  14. Classes, methods, variables declared as final can improve performance, so have the opportunity to estimate the JVM, then optimize.
  15. According to the Java code convention, final variable is constant, and usually constant names to uppercase:

    private final int COUNT = 10;

  16. For a collection of objects declared as final means that reference can not be changed, but to which you can add, delete, or change the content.
    private final List Loans = new ArrayList();
    list.add(“home loan”);  //valid
    list.add("personal loan"); //valid
    loans = new Vector();  //not valid

     

Guess you like

Origin blog.csdn.net/qq_40722284/article/details/85098818