[英]Is StringBuilder threadsafe (using it with parallelStream)?
My code: 我的代码:
StringBuilder sb = new StringBuilder();
events.parallelStream().forEach(event -> {
sb.append(event.toString());
sb.append("\n");
});
I don't care about the order of the events.toString()
in the final result. 我不关心最终结果中events.toString()
的顺序。 But I care that the events.toString()
will correctly appear one line after another, without mixing / messing up of course. 但我关心的是events.toString()
会正确地出现一行一行,当然没有混合/混乱。
Is parallelStream
(instead of stream
) safe in this regard? parallelStream
(而不是stream
)在这方面是否安全?
The better solution is to use 更好的解决方案是使用
events.parallelStream().map(event -> event+"\n").collect(Collectors.joining());
Or alternatively (thanks to @Holger): 或者(感谢@Holger):
events.parallelStream().map(Object::toString).collect(Collectors.joining("\n", "", "\n"));
In general avoid using forEach
as terminal operation for streams. 通常避免使用forEach
作为流的终端操作。 Usually reduction operations like collect
or reduce
are better alternatives. 通常, collect
或reduce
等减少操作是更好的选择。
No, it is not thread-safe. 不,它不是线程安全的。
This is the main difference between the old StringBuffer
and the new StringBuilder
- the former's methods are synchronized, while the latter's are not. 这是旧StringBuffer
和新StringBuilder
之间的主要区别 - 前者的方法是同步的,而后者不是。
It's not very useful to do it this way, even if you'd use StringBuffer
instead - the threads would have to wait on each other to write to the StringBuffer
. 以这种方式执行它并不是非常有用,即使您使用StringBuffer
- 线程也必须等待彼此写入StringBuffer
。
No, it is not. 不它不是。 As noted in its javadoc : 正如其javadoc中所述 :
A mutable sequence of characters. 一个可变的字符序列。 This class provides an API compatible with StringBuffer, but with no guarantee of synchronization . 此类提供与StringBuffer兼容的API,但不保证同步 。
Use StringBuffer
instead. 请改用StringBuffer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.