Java concurrency-thread security Policy __java concurrency

Source: Internet
Author: User
Tags closure concurrentmodificationexception
Thread Security Policy 1. Immutable Objects 1.1 Meet the conditionsWhen an object is created, its state cannot change the object is created correctly by all the fields of the final type (during object creation, this reference is not escaped, the class is declared final, the member is declared as a private member, the variable is set method, reference string type) 2. Declaring immutable objects 2.1 collections.unmodifiablexxx

Its main implementation is to pass the current collection object into the Collections.unmodifiablexxx method
Pass:

public static <K,V> map<k,v> Unmodifiablemap (map<. extends K,? extends v> m) {return
    new Unmodifia Blemap<> (m);
}

Returns a custom Unmodifiablemap object that allows the module to provide users with read-only access to internal mappings. The query performed on the returned map will read the specified mapping. Attempting to modify the returned mapping, whether modified directly or through its collection view, will cause the unsupportedoperationexception to be thrown.

Collection, List, set, map and so on we just need to declare the collection type object into this method, the collection type can not be modified.

Import Com.liuyao.concurrency.annotations.TreadSafe;

Import java.util.Collections;
Import Java.util.HashMap;
Import Java.util.Map;

/**
 * Created by Liuyao on 2018/4/17 17:15.
 * *
@TreadSafe public
class ImmutableExample2 {
    private  static map<integer,integer> map=new Hashmap<> ();
    static {
        map.put (1,2);
        Map.put (2,3);
        map= collections.unmodifiablemap (map);

    public static void Main (string[] args) {
        map.put (1,3);  Will throw an exception
        System.out.println (Map.get (1));
    }
2.2 immutablexxx

Guava: Collection, List, Set, and Map provide a method with initialization data that cannot be modified once the initialization is complete.

Package com.liuyao.concurrency.example.immutable;

Import com.google.common.collect.ImmutableList;
Import Com.google.common.collect.ImmutableMap;
Import Com.google.common.collect.ImmutableSet;
Import Com.liuyao.concurrency.annotations.ThreadSafe;

/**
 * Created by Liuyao on 2018/4/17 17:33.
 * *
@ThreadSafe public
class ImmutableExample3 {
    private final static immutablelist 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,5,6);

    Private final static immutablemap<integer,integer> Map2=immutablemap.<integer,integer>builder (). Put ( 1,2). Put (3,4)-build ();
    public static void Main (string[] args) {
//        List.add (4);        Map.put (1,3);
        System.out.println (Map.get (2));
    }
3. Thread ClosureAd-hoc Thread Closure: program-controlled implementation, worst of all, ignoring stack closures: local variables, no concurrency problems threadlocal thread closure: A particularly good closure method 4. Thread unsafe classes and writing

StringBuilder: Thread unsafe, method internal use, stack closed

StringBuffer: Thread safe, with synchronized, poor performance 4.1 SimpleDateFormat

is not thread safe, in the case of multithreading, an exception will occur.

multiple threads share one, thread is unsafe:

Private  static SimpleDateFormat simpledateformat=new SimpleDateFormat ("Yyyy-mm-dd");

    private static void Update () {
        try {
            simpledateformat.parse ("2018-04-19");
        } catch (ParseException e) {
            e.printstacktrace ();
        }
    

each time a new use is applied, thread safety:

private static void Update () {
    SimpleDateFormat simpledateformat=new simpledateformat ("Yyyy-mm-dd");
    try {
        simpledateformat.parse ("2018-04-19");
    } catch (ParseException e) {
        e.printstacktrace ();
    }
}
4.2 jodatime: Thread-Safe

Pom.xml

    <dependency>
        <groupId>joda-time</groupId>
        <artifactid>joda-time</ artifactid>
        <version>2.9</version>
    </dependency>

Usage:

private static DateTimeFormatter datetimeformatter= Datetimeformat.forpattern ("Yyyy-mm-dd");

private static void Update () {
    datetime.parse ("2018-04-19", DateTimeFormatter). ToDate ();
}
5. Synchronization Container

ArrayList hashset hashmap are thread unsafe. 5.1 ArrayList-> vector,stack

Although both methods are synchronized for vectors, there may be threads that are unsafe

import java.util.Vector;
 /** * Created by Liuyao on 2018/4/20 18:00.

    * * Public class VectorExample2 {private static vector<integer> vector=new vector<> ();
               public static void Main (string[] args {while (true) {for (int i = 0; i < i++) {
           Vector.add (i); Thread Thread1=new thread () {@Override public void run () {f
                   or (int i = 0; i < vector.size (); i++) {vector.remove (i);

           }
               }
           }; Thread Thread2=new thread () {@Override public void run () {for (int i = 0 ; I < vector.size ();
                   i++) {vector.get (i);
           }
               }
           };
           Thread1.start ();
       Thread2.start (); }
    }
}

Appeal two method execution, because the Get method at the time of the value, it is very likely that the other thread's Remove method has removed the element, so thrown an exception. Synchronization problems caused by differences in the order of execution of two threads. 5.2 HashMap-> HashTable (Key,value cannot be null) 5.3 collections.synchronizedxxx (list,map,set)

private static list<integer> list= collections.synchronizedlist (New arraylist<integer> ());
5.4 Collection Edge traversal edge deletion
Import Com.liuyao.concurrency.annotations.NotThreadSafe;
Import Java.util.Iterator;

Import Java.util.Vector;
 /** * Created by Liuyao on 2018/4/20 18:00. */@NotThreadSafe public class VectorExample3 {//java.util.concurrentmodificationexception public static void TEs
            T1 (vector<integer> v1) {for (Integer i:v1) {if (I.equals (3)) {v1.remove (i); }}//Java.util.ConcurrentModificationException public static void Test2 (Vector<intege
        R> v2) {iterator<integer> iterator=v2.iterator ();
            while (Iterator.hasnext ()) {Integer i=iterator.next ();
            if (I.equals (3)) {v2.remove (i); }}//Success public static void Test3 (Vector<integer> v3) {for (int i = 0; i < v3. Size ();
            i++) {if (V3.get (i). Equals (3)) {v3.remove (i); }} public static void Main (String[] args) {vector<integer> vector=new vector<> ();
        Vector.add (1);
        Vector.add (2);
        Vector.add (3);
    Test3 (vector); }
}

When a collection traversal is a remove operation on a collection, it causes:

final void Checkforcomodification () {
        if (modcount!= expectedmodcount)
            throw new Concurrentmodificationexception ();
    }

The above Modcount and expectedmodcount are not equal, throw an exception, so use the Foreach loop and iterator loop, as far as possible do not in the early operation of the remove operation, you can first mark, such as traversal after the remove operation. A single-threaded error occurs, and in multi-threaded situations, the error is greater. 6. Concurrent containers J.U.C 6.1 ArrayList-> copyonwritearraylist

private static list<integer> arraylist=new copyonwritearraylist<integer> ();

Write operation replication, when a new element is added to the array, first copy out of the original array, write in the new array, and then point the original array to the new array. The entire write operation is under the protection of the lock, mainly for multiple threads concurrency, copying multiple arrays to confuse the array.

Because the write operation to copy elements, if the element is more in case, may lead to GC, can not be used for real-time reading of the scene, because the copy array and the new elements need time, so can not meet the real-time, but to meet the final result is correct.

Copyonwritearraylist is suitable for reading and writing less. When you can't guarantee copyonwritearraylist exactly how much data to put, it is recommended not to use, because each update operation, will copy operation, this price is a bit large, may cause performance failure.

Three ideas:
1. Read and write separation, reading do not need to lock, write to add locks
2. Final consistency to ensure that the end is right
3. Additional space to resolve concurrent conflicts 6.2 Hashset,treeset-> Copyonwritearrayset,concurrentskiplistset

The Copyonwritearrayset bottom implementation is copyonwritearraylist, suitable for small set, read operation is greater than write operation. Add,set,remove operation cost is large.

Concurrentskiplistset is a new class of JDK6, is a natural sort, and can customize the comparer, based on the amount of map collection, multithreading is thread-safe for add,remove,contains, for Addall,removeall , Containsall is not synchronized, they call the bottom of these individual methods above, the bulk operation can only be thread-safe, the need to manually add locks.

Concurrentskiplistset does not allow the use of empty elements, and it cannot reliably distinguish between the element's return value and the element that does not exist. 6.3 Hashmap,treemap-> concurrenthashmap,concurrentskiplistmap

Concurrenthashmap does not allow null values and is optimized for reading

Concurrentskiplistmap key order, support for higher concurrency, access time and number of threads does not matter, the number of concurrent threads, the effect is more obvious.

7. Secure shared Object Policy-summary thread limit : A thread-restricted object, wired exclusive, and can only be modified by the thread that owns it shared Read Only : A shared, read-only object that can be accessed concurrently by multiple threads without additional synchronization, but no thread could modify it thread-safe object : A thread-safe object or container that internally passes the synchronization mechanism to ensure thread safety. So other threads can freely access it through the public interface without additional synchronization protected objects : A protected object can only be accessed by obtaining a specific lock.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.