Be careful when modifying the SET SIZE

Source: Internet
Author: User
Tags concurrentmodificationexception

Java is the most commonly used collection, and is in performance considerations. Most people no longer use the Vector Method for synchronization. The new collection Library brings faster performance and more error usage possibilities. The performance improvement of the new collection library is mainly to remove the synchronization method. It can be imagined that there must be a data consistency problem during synchronous access. To prevent other errors caused by inconsistent data, the new collection library uses the Fast-Fail Mechanism during design ), this means that the current set size is determined to be modified every time the set is traversed. If the set size is modified, a ConcurrentModificationException is thrown immediately to stop the program from running. Therefore, after the set Initialization is complete, the size of the set should not be modified in another place. Let's look at the example below:

  1. PackageCom. bhr. ioat. testcollection;
  2. ImportJava. util .*;
  3. Public ClassTestRemove
  4. {
  5. Public Static VoidMain (String[] Args)
  6. {
  7. CollectionCltn =New ArrayList();
  8. For(IntI = 0; I <100000; I ++ ){
  9. Cltn. add (New Integer(I ));
  10. }
  11. NewOtherThread (cltn). start ();
  12. Try{
  13. Thread. Sleep (1000 );// Sleep 1 second, in order to ensure the new thread start up.
  14. }Catch(ExceptionE ){
  15. E. printStackTrace ();
  16. }
  17. IteratorIt = cltn. iterator ();
  18. While(It. hasNext ()){
  19. ObjectObj = it. next ();
  20. Cltn. remove (obj );
  21. // It. remove ();
  22. System. Out. println ("Remove one element from collection ");
  23. Break;
  24. }
  25. }
  26. }
  27. ClassOtherThreadExtends Thread 
  28. {
  29. Public CollectionCltn _;
  30. PublicOtherThread (CollectionCltn ){
  31. Cltn _ = cltn;
  32. // Cltn _ = (Collection) (ArrayList) cltn). clone ());
  33. }
  34. Public VoidRun (){
  35. IteratorIt = cltn _. iterator ();
  36. While(It. hasNext ()){
  37. ObjectObj = it. next ();
  38. System. Out. println (obj );
  39. }
  40. }
  41. }

The program is very simple. Initialize an ArrayList of 100000 size and pass it to another class. Then, delete an element in the set. You will find that the ConcurrentModificationException will be thrown immediately.
Can't we delete elements? Should we continue using Vector? Of course not. It doesn't make sense if a new set appears. There are two solutions: (1) the set is only used in one place, which naturally has no concurrency problem, but it still cannot be modified. If the elements in the set are deleted in a loop, you must call the remove Method of Iterator instead of the remove method of Collection. The former will modify the value of Iterator after deletion, so that the loop can continue to process the set because it is not modified, the latter is called without modifying the value in the Iterator. If you continue the loop, an exception is thrown. As for adding elements, the Iterator does not provide the corresponding method. Therefore, if you add elements in the loop, you can only jump out of the loop after adding the elements. (2) If the same set is used in multiple places, simply do not delete it. In this case, the set size should not be modified. If you decide that the modification of the set size will not affect the normal logic of the program, in this case, you have to clone one.
The above just summed up a little practical experience, if you have a better way, You can exchange, E-mail: zhvfeng@hotmail.com

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.