Is JAVA StringJoiner Thread-Safe?

Unlike StringBuffer methods (like append()) which are synchronized, methods of StringJoiner (like add()) are not synchronized. Thus it is not thread-safe.

Source code from OpenJDK:

  • StringJoiner
  • StringBuffer

There is zero information in the documentation that would even hint a thread safety property. But, it has a method like StringJoiner::merge that is very often overlooked. This is used to combine two StringJoiners together by two separate threads; and is used internally by the stream API when multiple threads are involved.

So, no, it is not thread safe at all; but can be used to merge two different StringJoiner(s).

Tags:

Java