How to limit the flow for sequential start and prevent its parallel operation?

I have a method that returns a stream that is generated from a custom separator; the separator is not tread protected. Since the spliterator is not tread-protected and it maintains state, I want it to not work in parallel. Is there a way to prevent the returned thread from running in parallel?

I could not find documentation or examples that do this. I found a method sequential()in the class BaseStream, but that does not stop the user from calling parallel()to get a parallel thread.

+4
source share
2 answers

A parallel thread calls trySplit()your splitter method to split your task into several parts. It is absolutely legal to bring back nullfrom trySplit(), saying that "I refuse to share." In this case, the thread created from your separator will execute sequentially, even if it .parallel()was explicitly called.

parallelism, AbstractSpliterator. trySplit(), , tryAdvance(), spliterator , . " ", , .

, , Spliterator . trySplit(), , spliterator spliterator . , , .

+2

, , . , , . , .

Thread, API:

Thread.currentThread().getId()

, . Exception "Not Thread-Safe!". .

0

Source: https://habr.com/ru/post/1616805/


All Articles