executorservice - java.util.concurrent.ExecutionException: java.util.ConcurrentModificationException -
i getting concurrent modification exception when executing following code:
mymap global variable , hashmap
callable<string> task = new callable<string>() { @override public string call() { mymap.put("myid", "id2"); mymap.put("myname", "joe"); string id = mymap.get("myid"); system.out.println("id is: "+ id+ ", mymap before: "+mymap.tostring()); mymap.remove("myid"); system.out.println("id is: "+ id+ ", mymap after: "+mymap.tostring()); return id; } }; list<callable<string>> tasks = collections.ncopies(7, task); executorservice executorservice = executors.newfixedthreadpool(7); list<future<string>> futures = executorservice.invokeall(tasks); list<string> resultlist = new arraylist<string>(futures.size()); (future<string> future: futures){ resultlist.add(future.get()); }
the exception thrown lines:
resultlist.add(future.get());
and
system.out.println("id is: "+ id+ ", mymap after: "+mymap.tostring());
however if try
system.out.println("srcnode after: "+srcnode.tostring()+ ", id: "+id);
instead error seems disappear. clues on whats going on?
since there multiple threads modifying same instance - error. regarding,
why 1 point statement works , not other
threads not guaranteed provide same outcome every time. possible if execute program many times, different output (no exception, exception @ different line etc).
example - executed program 3 times, execution successful 2 times , got concurrent exception third time.
to conclude, 1 cannot guarantee order or timing of execution of threads. in order avoid these errors use synchronization or hashtable thread safe - comes @ cost of performance. also, having mymap declared local variable method work - since each thread have own copy of local variable - assuming instance variable reason.
Comments
Post a Comment