Spliterator: Thread-Safe or not?

1.1k Views Asked by At

I am looking into the documentation of the Spliterator and according to it, the Spliterator is not thread-safe:

Despite their obvious utility in parallel algorithms, spliterators are not expected to be thread-safe; instead, implementations of parallel algorithms using spliterators should ensure that the spliterator is only used by one thread at a time. This is generally easy to attain via serial thread-confinement, which often is a natural consequence of typical parallel algorithms that work by recursive decomposition.

But, in its further documentation, which states a contradictory statement to the above statement:

Structural interference of a source can be managed in the following ways (in approximate order of decreasing desirability):

The source manages concurrent modifications. For example, a key set of a java.util.concurrent.ConcurrentHashMap is a concurrent source. A Spliterator created from the source reports a characteristic of CONCURRENT.

So does that mean a Spliterator generated from a thread-safe collection would be thread-safe? Is it right?

1

There are 1 best solutions below

0
On BEST ANSWER

No, a Spliterator reporting the CONCURRENT characteristic will have a thread safe source, which implies that it can iterate over it safely even when the source gets modified concurrently. But the Spliterator itself may still have state that must not be manipulated concurrently.

Note that your cite stems from a description of how “structural interference of a source can be managed”, not about the spliterator’s behavior in general.

This is also provided at the documentation of the CONCURRENT characteristic itself:

Characteristic value signifying that the element source may be safely concurrently modified (allowing additions, replacements, and/or removals) by multiple threads without external synchronization. If so, the Spliterator is expected to have a documented policy concerning the impact of modifications during traversal.

Nothing else.

So the consequences of these characteristics are astonishing small. A Spliterator reporting either CONCURRENT or IMMUTABLE will never throw a ConcurrentModificationException, that’s all. In all other regards, the differences between these characteristics will not be recognized by the Stream API, as the Stream API never performs any source manipulations, in fact, it doesn’t actually know the source (other than indirectly through the Spliterator), so it couldn’t do such manipulations nor detect whether a concurrent modification has happened.