java - Modify a list while it is being iterating -


When I was checking my answer to get the output for the question, then given the following output to the given list content Found:

  // Add some wire to the list list. Add ("Item 1"); List.add ("Item 2"); List.add ("Item 3"); List.add ("item 4");   

Output:

  Item 1 item 2 in the exception thread "Thread-0" java.util.ConcurrentModificationException at java.util.ArrayList $ Itr.checkForComodification (ArrayList.java:859) at java.util.ArrayList $ Itr.next (ArrayList.java:831) on Com. Com.akefirad.tests.Main $ 1.run (main.java.3) at java.lang.Thread.run (Thread.java:745)   

But if any of the following lists Uses:

  // Add some string to the list list. Add ("Item 1"); List.add ("Item 2"); List.add ("Item 3");   

Output:

  item 1 item 2   

There is no exception in output and only two first items printed Will someone be able to explain why this happens? Thank you

Note: The code is.

Edit: My question is that I do not have a third item printed (meaning list is modified) and there is no exception.

To edit the code to generate exceptions, please note the list contents:

  public class key {public static zero main (string [] args) Interrupted expression Throws {Final ArrayList & lt; String & gt; List = New Arrestist & lt; String & gt; (); List.add ("item 1"); List.add ("Item 2"); List.add ("Item 3"); List.add ("item 4"); Thread thread = New thread (New Runnabel) {@ Override Public Wide Run (for (string S: list) {System.out.println ()); Try {Thread, sleep (1000);} Hold (Interrupted) {E.printStackTrace ();}}}}); Thread.start (); Thread.Sleep (2000); List.remove (0); }}    

Fundamentally, you are modifying a list in a thread , While backing it in another, and the list you use supports not the implementation.

This ArrayList Iterter implementation only detects invalid modicifications on calls to call next () , not For hasNext () . So if you come to the last iteration of the first remove call, you will not get an exception - hasNext () just False will come back on the other side, if is removed () before the last call is next () (and if it is viewed on another thread If the memory model comes to play here) then you will get an exception. For example, if you change your in-loop sleep to thread. (2500) An exception will be found if the start of the walk starts, because remove () <

if you want to use a list in multiple threads and at least one of them is modifying it, then you The implementation should be used which is copyOnRightArerealist .

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -