Parallel For Loop java has race condition -


i have piece of code runs in loop parallelize. use of executorservice makes code fast getting inconsistent results, possibly due race condition. there parallel loop works fast 1 , consistent?

executorservice exec = executors.newfixedthreadpool(8);      try{         (string tour : tours)             {                 if (valid)                 {                    exec.submit(() ->                      {                         double len1 = tsp.tourlen(tour, cities); //expensive sequentially                         if (bestlen == -1 || len1 < bestlen)                         {                             bestlen = len1;                             besttour = tour;                         }                     });                 }             }              system.out.println("\n     best tour len: " + bestlen);             system.out.println("\n          best tour: " + besttour);          }         {             exec.shutdown();         } 

the way heavy processing in background thread, load hashmap<string, double>, avoid concurrency issues. (tour, len1)

then iterate on map, foreach lambda hashmap.foreach((k,v) -> /*comparison here*/);

note:

though mentioned synchronized above ,for issue doubt help, because, you can't comparisons on data not have yet.

source: how each hashmap?


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -