I've a ConcurrentLinkedQueue
that's accessed by multiple threads; the objects in it are immutable. In one thread, I need a snapshot of the data, which I'm doing by calling stream
on it. Is it safe? I'm aware of the non-interference requirement, but it seems to be talking about modification from one of the stream operations ("stream pipelines whose source might not be concurrent should never modify the stream's data source"), not necessarily externally. Besides, the ConcurrentLinkedQueue
is designed for concurrent access, so there's that.
From the documentation in link you have provided
For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose Spliterator reports the CONCURRENT characteristic
From documentation of the SplitIterator (its CONCURRENT characteristic)
static final int CONCURRENT
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.
This is implementation from Collection interface stream method (which is not overridden in ConcurrentLinkedQueue)
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
So as long as ConcurrentLinkedQueue uses CONCURRENT SplitIterator (which it does) I would assume you can safely iterate your ConcurrentLinkedQueue using stream().