英文:
Are Guava's toImmutableSet() and toImmutableList() collectors thread-safe?
问题
Guava提供了像ImmutableSet.toImmutableSet()
和ImmutableList.toImmutableList()
这样的收集器。它们是否线程安全?在并行流中使用它们是否安全?
据我所见,它们使用的是非线程安全的常规构建器:
private static final Collector<Object, ?, ImmutableSet<Object>> TO_IMMUTABLE_SET =
Collector.of(
ImmutableSet::<Object>builder,
ImmutableSet.Builder::add,
ImmutableSet.Builder::combine,
ImmutableSet.Builder::build);
另一方面,Collector.of()
的第一个和第三个参数使人怀疑JDK可能会为每个并行线程创建单独的构建器,然后组合它们的结果以实现线程安全。
英文:
Guava has collectors like ImmutableSet.toImmutableSet()
and ImmutableList.toImmutableList()
. Are they thread-safe? Is it safe to use them with parallel streams?
As far as I see the use the regular builders which are not thread-safe:
private static final Collector<Object, ?, ImmutableSet<Object>> TO_IMMUTABLE_SET =
Collector.of(
ImmutableSet::<Object>builder,
ImmutableSet.Builder::add,
ImmutableSet.Builder::combine,
ImmutableSet.Builder::build);
On the other hand, the first and third parameters of Collector.of()
makes it suspicious that JDK could create a separate builder for every parallel thread and combine their result to make it thread-safe.
答案1
得分: 3
I believe answer to the question you're supposed to ask is different than to what you actually asked.
No, the collectors are not thread-safe per se (ex. ImmutableList builder performs unsynchronized operations on Object[]
), but more importantly collectors don't have to be thread safe to be useful for parallel stream operations. For that see answer from Stuart Marks to question "Parallel streams, collectors and thread safety":
Can non-concurrent collectors be safely used with a parallel stream or should I only use the concurrent versions when collecting from a parallel stream?
It is safe to use a non-concurrent collector in a collect operation of a parallel stream.
For more details, please read the answer and links provided to documentation / contracts of various java.util.stream
classes.
英文:
I believe answer to the question you're supposed to ask is different than to what you actually asked.
No, the collectors are not thread-safe per se (ex. ImmutableList builder performs unsynchronized operations on Object[]
), but more importantly collectors don't have to be thread safe to be useful for parallel stream operations. For that see answer from Stuart Marks to question "Parallel streams, collectors and thread safety":
> > Can non-concurrent collectors be safely used with a parallel stream or should I only use the concurrent versions when collecting from a parallel stream?
>
> It is safe to use a non-concurrent collector in a collect operation of a parallel stream.
For more details, please read the answer and links provided to documentation / contracts of various java.util.stream
classes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论