Could you please tell is there any way in which concurrent modification exception could occur in a single threaded environment also the below application which I am posting consists of two threads , please tell me can I see the same exception in a single thread also..please advise
package concurrentmodificationError;
import java.util.*;
class ItrDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("Amit");
v.add("Rahul");
v.add(1,"Nitin");
v.addElement("Ankit");
System.out.println("There are "+v.size()+"elements in the vector ");
final Iterator itr=v.iterator();
Thread th=new Thread() {
public void run()
{
System.out.println("New Thread started,traversing elements of vector...");
System.out.println("Contents of vector are...");
while(itr.hasNext())
{
System.out.println(itr.next());
try
{
Thread.sleep(2000);
}
catch(Exception e1)
{
}
}
}
};// end of annomyous class
System.out.println("Suspending main thread and starting a new thread for traversing the contents of vector...");
th.start();
try
{
Thread.sleep(1000);
}
catch(Exception e1)
{
}
System.out.println("main thread resumed,modifying vector...");
v.remove("Ankit");
v.add("Puneet");
v.add("Raman");
System.out.println("Vector Modified , Ankit removed and Puneet & Raman added.");
}
}
yeah I got it folks that in the single threaded enviorement this error can comes.. as shown in below piece of code..
System.out.println("Content of list are : ");
ListIterator itr1=list.listIterator();
while(itr1.hasNext())
{
list.add(new Emp("Anand","Manager",56000)); //
Emp e=(Emp)itr1.next();
e.display();
}
Please advise what are the ways to overcome it..so that does not get this error..!!Please advise
A
ConcurrentModificationExceptioncan be thrown in a single thread environment. It is used whenever an object is modified in a context where it shouldn’t, not necessarily in another thread.Example: