I have a piece of code that runs in a loop that I would like to parallelize. The use of ExecutorService makes the code very fast but I am getting inconsistent results, possibly due to a race condition. Is there another parallel for loop that works fast like this one and is always consistent?
ExecutorService exec = Executors.newFixedThreadPool(8);
try{
for (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);
} finally
{
exec.shutdown();
}