I have a code which has two executors, executorShops
and executorSections
, the first one is not important though.
I create as many tasks as sections there are (three in this example), however, only two are executed at the same time.
Every task updates a shared list, but, the problem is only the first two threads update it correctly. The third thread, which has been queued, won't update it.
Here's the code where tasks are created:
Runnable task = () -> {
LOG.info("Llamamos al ScraperManager para obtener el scraper de " + shop.getName());
Scraper scraper = ScraperManager.getScraper(shop);
LOG.info("Scraper de " + shop.getName() + " obtenido");
ExecutorService executorSections = Executors.newFixedThreadPool(Properties.MAX_THREADS_SECTIONS);
Set<Callable<List<Product>>> listOfTasks = new HashSet<>();
for (int j = 0; j < shop.getSections().size(); j++)
{
final Section section = shop.getSections().get(j);
Callable<List<Product>> taskSection = () -> scraper.scrap(shop, section);
listOfTasks.add(taskSection);
}
try
{
List<Future<List<Product>>> listOfFutures = executorSections.invokeAll(listOfTasks);
List<Product> productList = listOfFutures.get(shop.getSections().size() - 1).get();
RestClient restClient = new RestClient(new URL(Properties.SERVER));
restClient.saveProducts(productList, shop);
countDownLatch.countDown();
executorSections.shutdown();
} catch (InterruptedException | ExecutionException ex ) {
...
} catch (MalformedURLException ex) {
...
}
};
And here's the scrap task:
public class ShopScraper implements Scraper
{
private static List<Product> productList = Collections.synchronizedList(new ArrayList<>());
private static final ThreadLocal<Boolean> threadFinished =
new ThreadLocal<Boolean>()
{
@Override
protected Boolean initialValue()
{
return false;
}
};
@Override
public List<Product> scrap(Shop shop, Section section) throws IOException
{
// add products to the list
return productList;
}
}
EDIT: If I limit the number of threads to 1, then the second and third thread don't update the list.
Does anyone know what I did wrong?
Thanks in advance,