Search code examples
javamultithreadingthread-safetyjava-8stringbuilder

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?


Solution

  • The better solution is to use

    events.parallelStream().map(event -> event+"\n").collect(Collectors.joining());
    

    Or alternatively (thanks to @Holger):

    events.parallelStream().map(Object::toString).collect(Collectors.joining("\n", "", "\n"));
    

    In general avoid using forEach as terminal operation for streams. Usually reduction operations like collect or reduce are better alternatives.