Java Collection Learning (iv) Fail-fast summary

Source: Internet
Author: User
Tags static class thread concurrentmodificationexception

Fail-fast Summary (through ArrayList to explain the fail-fast principle, solution)

In front, we have learned the ArrayList. Next, we take ArrayList as an example to understand the fail-fast mechanism of iterator.

1 Fail-fast Profile

The fail-fast mechanism is an error mechanism in the Java Collection (Collection). Fail-fast events can occur when multiple threads operate on the contents of the same collection.
For example, when a thread a passes through a iterator to traverse a collection, if the content of the collection is changed by another thread, then thread a accesses the collection and throws a Concurrentmodificationexception exception to produce the Fail-fast event.

Before introducing the rationale of the fail-fast mechanism in detail, an example is used to understand fail-fast.

2 Fail-fast Sample

Sample code: (Fastfailtest.java)

Import java.util.*;
     
Import java.util.concurrent.*;
 /* * @desc the Fast-fail test program in the Java collection. * * Fast-fail Event conditions: When multiple threads operate on collection, if one of the threads traverses the collection through iterator, the contents of the collection are changed by other threads
 ; The concurrentmodificationexception exception is thrown.
 * Fast-fail Solution: The Fast-fail event is not generated by handling the corresponding class under the Util.concurrent collection package. * * In this case, test the ArrayList and Copyonwritearraylist respectively.
 ArrayList produces Fast-fail events, and Copyonwritearraylist does not produce fast-fail events. * (01) When using ArrayList, it will produce Fast-fail event, throw Concurrentmodificationexception exception, and define as follows: * private static list<string
 > list = new arraylist<string> (); * (02) When used copyonwritearraylist, does not produce fast-fail event; the definition is as follows: * private static list<string> List = new COPYONWR
 Itearraylist<string> (); * * @author Skywang * * * public class Fastfailtest {private static list<string> List = new Arraylist<s
    Tring> ();
    private static list<string> List = new copyonwritearraylist<string> ();
         
  public static void Main (string[] args) {      Start two threads at the same time to operate the list!
        New Threadone (). Start ();
    New Threadtwo (). Start ();
     
        private static void Printall () {System.out.println ("");
        String value = null;
        Iterator iter = List.iterator ();
            while (Iter.hasnext ()) {value = (String) iter.next ();
        System.out.print (value+ ","); }/** * Adds a 0,1,2,3,4,5 to the list followed by Printall () to traverse the entire list/private static class after each added number Threado
            NE extends Thread {public void run () {int i = 0;
                while (i<6) {List.add (string.valueof (i));
                Printall ();
            i++; }}/** * Adds 10,11,12,13,14,15 to the list, and after each add a number, it traverses the entire list via printall () * * Private stat
            IC class Threadtwo extends Thread {public void run () {int i = 10;
             while (i<16) {List.add (string.valueof (i));   Printall ();
            i++; }
        }
    }
     
}

Run Result:
Run the code, throw an exception java.util.concurrentmodificationexception! That is, produce Fail-fast event!

Results show:
() Fastfailtest the new Threadone (). Start () and New Threadtwo (). Starting () starts two threads at the same time to manipulate the list.
Threadone Thread: Add 0,1,2,3,4,5 to the list in turn. After each additional number is added, the entire list is traversed by printall ().
Threadtwo Thread: Add 10,11,12,13,14,15 to the list in turn. After each additional number is added, the entire list is traversed by printall ().
(02) When a thread traverses the list, the contents of the list are changed by another thread, and a Concurrentmodificationexception exception is thrown, resulting in a fail-fast event.

3 Fail-fast Solutions

Fail-fast mechanism is a kind of error detection mechanism. It can only be used to detect errors because the JDK does not guarantee that the fail-fast mechanism will occur. If you use the fail-fast mechanism in a multithreaded environment, it is recommended to replace the "classes under Java.util package" with the "classes under Java.util.concurrent".
So, in this case, just replace the ArrayList with the corresponding class in the Java.util.concurrent package.
That is, the code

private static list<string> List = new arraylist<string> ();

Replaced by

private static list<string> List = new copyonwritearraylist<string> ();


The solution can be solved.

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.