0

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();
        }

1 Answers1

0

The way I would do this is do the heavy processing in the background thread, load that into a HashMap<String, Double>, to avoid concurrency issues. (tour, len1)

Then iterate over that map, with a foreach lambda hashmap.foreach((k,v) -> /*comparison here*/);

Note:

Though I mentioned synchronized above ,for this issue I doubt it will help, because, You can't do comparisons on data you do not have yet.

source: How to for each the hashmap?

Community
  • 1
  • 1
Adam Forbis
  • 461
  • 3
  • 11