How to collect data from parallel running tasks using GPars and Groovy

1.2k Views Asked by At

GPars documentation says we should not do:

def thumbnails = []
images.eachParallel {thumbnails << it.thumbnail} // Concurrently accessing a not-thread-safe collection of thumbnails? Don't do this!

source: http://www.gpars.org/webapp/guide/index.html#_avoid_side_effects_in_functions

I want to write a similar kind of code, where parallel executing methods need to write to a common List. How can I do that?

1

There are 1 best solutions below

0
On

The code you have shown is not thread-safe - multiple different threads will try adding elements to the list in parallel. What may happen is two (or more) threads try to add an element at the same index, so the last thread will actually replace what the previous one did.

Instead try following:

def thumbnails = images.collectParallel {it.thumbnail}

or

def thumbnails = images.parallel.map {it.thumbnail}

It's thread-safe and you get a list of all thumbnails as a result.