java - Example of exception in ArrayList? -


I am using ArrayList and if I try to access the same list without multiple thread synchronization, then I Want an example of exception? I have done this in a single threaded application, in which if we remove an element from the list, iterates, concurrent improvement throws the acupineine, but I want to get it in a multi-threaded environment. If someone can give me an example of what would be highly appreciated?

  package com.test2; Expands the public class threads threshold {list list = new arrelisted & lt; String & gt; (); @ Override Public Wide Run () {list.add ("1"); List.add ("2"); List.add ("3"); List.add ("4"); List.add ("5"); Try {Thread.sleep (1); } Grip (Interrupted e) e.printStackTrace (); } List.add ("6"); List.add ("7"); List.add ("8"); Iterator & LT; String & gt; This = list.iterator (); While (this hasNext ()) {System.out.println (it.next ()); }} Public static zero main (string [] args) {thread th1 = new thread test (); Thread Th 2 = New Thread Test (); Thread Th3 = New Thread Test (); Th1.start (); Th2.start (); Th3.start (); Try {th1.join (); Th2.join (); Th3.join (); } Grip (Interrupted e) e.printStackTrace (); You are reaching a different list frequency in each of your threads I / O  
  list list = new array list & lt; String & gt; ();   

This declares an example field , therefore, each call to new thread test () creates a new list for all Thread Test To use the same list of examples, try to make the field stable (i.e. class field ):

  Fixed list list = new array list & lt; String & gt; ();  How  may be an error, take a look at this:  
  add public boolean (ee) {confirmCapacityInternal (size + 1); // increase modCount !! Element data [size ++] = e; Back true; }   

If two threads add at the same time, they can process the elementData [size ++] = e statement at the same time Time. ; Therefore, two threads can be written in the same index in the elementData array.

Even if size is declared unstable , size ++ operation not atom For example that an operation like size ++ may fail in a multithreaded environment.

Finally, if you do not know whether the is unstable in Java context and atomic midi, you really need to read on concurrent programming in Java before you can get any multi -If writing code, this will be a meaningful investment because you will save many headaches by understanding these concepts.

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 -