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. But I care that the events.toString()
will correctly appear one line after another, without mixing / messing up of course.
Is parallelStream
(instead of stream
) safe in this regard?
Because StringBuilder is not a synchronized one whereas StringBuffer is a synchronized one. When using StringBuilder in a multithreaded environment multiple threads can acess the StringBuilder object simultaneously and the output it produces can't be predicted hence StringBuilder is not a thread safe...
StringBuffer is synchronized and therefore thread-safe. StringBuilder is compatible with StringBuffer API but with no guarantee of synchronization. Because it's not a thread-safe implementation, it is faster and it is recommended to use it in places where there's no need for thread safety.
The parallelStream() method of the Collection interface can be used to create a parallel stream with a collection as the datasource. No other code is necessary for parallel execution, as the data partitioning and thread management for a parallel stream are handled by the API and the JVM.
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.
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
.
No, it is not. As noted in its javadoc:
A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
Use StringBuffer
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With