Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 442
seinecle Avatar asked May 27 '15 12:05

seinecle


People also ask

Why is StringBuilder not Threadsafe?

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...

Which is Threadsafe StringBuilder or StringBuffer?

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.

What is parallelStream?

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.


2 Answers

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.

like image 146
Jesper Avatar answered Sep 28 '22 13:09

Jesper


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.

like image 21
Luiggi Mendoza Avatar answered Sep 28 '22 14:09

Luiggi Mendoza