Imagine I have a collection input, which contains approx. 100000 objects.
There is a thread pool of workers, each of which
output collection.After all items in input have been processed, another routine takes output and does something with it.
I need the thread pool in order to process input as fast as possible. Every element of input should be processed exactly one time.
The order, in which the elements are processed, is irrelevant (both for input and output). output is write-only - the workers will only write there and won't do any other operations on output.
There are two parts of the problem, where thread safety is important:
input, other workers notice it and don't process the same element.output collection.Questions:
input collection ( ConcurrentLinkedQueue? ) ?LinkedList for the output collection (if 2 threads try to add different objects to the list at the same time, can it occur that one of the objects won't be saved) ?CLQ is fine for the input given your constraints, just be careful when polling size() for checking the termination of the input: as mentioned in the doc, it's not a constant time operation.
For the output, I doubt LinkedList is thread-safe, even just for adding. Adding means altering the state of the head node, and if two thread add at the same time this may create issues and detached elements.
You can use another CLQ or a LinkedBlockingDeque . There is also a simpler SynchronizedLinkedList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With