Use Java Collection classes in multithreading

Source: Internet
Author: User
Tags concurrentmodificationexception

In a Java Collection class, when a thread iterates on the Collection, it usually does not allow another thread to linearly modify the Collection. In these cases, the iteration results are usually uncertain. If this behavior is detected, some iterator implementations, including all common collection implementations provided by JRE, may throw this exception. The iterator that executes this operation is called the fast failure iterator, because the iterator quickly fails completely without the risk of any uncertain behavior at a certain time in the future.

Therefore, when one thread tries to iterate the ArrayList data, another thread will encounter an error and throw ConcurrentModificationException.

For example, the following code:

 
 
  1. final List<String> tickets = new ArrayList<String>(); 
  2. for (int i = 0; i < 100000; i++) { 
  3.    tickets.add("ticket NO," + i); 
  4. System.out.println("start1..."); 
  5. for (int i = 0; i < 10; i++) { 
  6.    Thread salethread = new Thread() { 
  7.        public void run() { 
  8.            while (tickets.size() > 0) { 
  9.                tickets.remove(0); 
  10.                System.out.println(Thread.currentThread().getId()+"Remove 0"); 
  11.            } 
  12.        } 
  13.    }; 
  14.    salethread.start(); 
  15. System.out.println("start2..."); 
  16. new Thread() { 
  17.    public void run() { 
  18.        for (String s : tickets) { 
  19. System.out.println(s); 
  20.        } 
  21.    } 
  22. }.start(); 

After the above program runs, an exception is thrown somewhere:

Java. util. ConcurrentModificationException

At java. util. ArrayList $ Itr. checkForComodification (Unknown Source)

At java. util. ArrayList $ Itr. next (Unknown Source)

At mytest. mytestpkg. Tj $ 2.run( corner stone. java: 138)

If the Vector is synchronized by threads, is it right to change the ArrayList to the Vector?

The answer is no. In fact, both ArrayList and Vector must follow the fail-fast detection mechanism as long as the Collection interface is implemented. That is, during iteration, the element of the set cannot be modified. Once this rule is found to be invalid, an exception is thrown.

In fact, the thread synchronization of Vector to ArrayList is reflected in whether the collection elements are dirty read. That is, ArrayList allows dirty reading, while the special mechanism of Vector does not, but the efficiency will be poor.

For example, if there are 10 threads in a set to delete elements from the set, each element can only be deleted by one thread, it is impossible to delete an element from multiple threads.

For example, the following code:

 
 
  1. final List<String> tickets = new ArrayList<String>(); 
  2. for (int i = 0; i < 100000; i++) { 
  3.    tickets.add("ticket NO," + i); 
  4. System.out.println("start1..."); 
  5. for (int i = 0; i < 10; i++) { 
  6.    Thread salethread = new Thread() { 
  7.        public void run() { 
  8.            while (true) { 
  9. if(tickets.size()>0) 
  10. System.out.println(Thread.currentThread().getId()+ tickets.remove(0)); 
  11. else 
  12. break; 
  13.            } 
  14.        } 
  15.    }; 
  16.    salethread.start(); 

The for loop constructs 10 threads to delete data in the same set. Theoretically, it can only be deleted 100000 times. However, after the execution, the output is deleted 108494 times, many of which are deleted by multiple threads, such as the following output segment:

17. ticket NO, 35721

14. ticket NO, 35699

11. ticket NO, 35721

18 ticketno, 35721

17. ticket NO, 35729

11. ticket NO, 35729

14. ticket NO, 35729

17. ticket NO, 35729

14. ticket NO, 35734

17. ticket NO, 35734

13. ticket NO, 35721

We can see that 35721,35729 has been deleted by multiple threads. This is actually caused by dirty reading. The solution is to lock the ArrayList so that only one thread can operate the ArrayList at the same time.

Modify the code and the synchronized keyword so that the thread that gets the lock object can run. This ensures that there is only one set of thread operations at the same time.

 
 
  1. final List<String> tickets = new ArrayList<String>(); 
  2. for (int i = 0; i < 100000; i++) { 
  3.    tickets.add("ticket NO," + i); 
  4. System.out.println("start1..."); 
  5. final Object lock=new Object(); 
  6. for (int i = 0; i < 10; i++) { 
  7.    Thread salethread = new Thread() { 
  8.        public void run() { 
  9.            while (true) { 
  10. synchronized(lock) 
  11. if(tickets.size()>0) 
  12. System.out.println(Thread.currentThread().getId()+ tickets.remove(0)); 
  13. else 
  14. break; 
  15.            } 
  16.        } 
  17.    }; 
  18.    salethread.start(); 

The result is accurate.

Of course, without the synchronized keyword, direct use of vector or Collections. synchronizedList is also the same effect:

 
 
  1. final List<String> tickets =java.util.Collections.synchronizedList(new ArrayList<String>()); 
  2. final List<String> tickets =new Vector<String>(); 

Both vector and Collections. synchronizedList are synchronized by threads to avoid dirty reads.

This article is from the "one blog" blog, please be sure to keep this source http://cnn237111.blog.51cto.com/2359144/1135527

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.