rishabh
rishabh

Reputation: 133

Is JAVA StringJoiner Thread-Safe?

Can anyone tell me if StringJoiner is thread-safe or not?

I know the difference between StringBuilder and StringBuffer but not able to find information about StringJoiner.

Upvotes: 7

Views: 2251

Answers (4)

S.K.
S.K.

Reputation: 3677

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:

Upvotes: 8

Eugene
Eugene

Reputation: 120848

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

Upvotes: 2

Gimhani
Gimhani

Reputation: 1375

StringJoiner (in java.util) is different from StringBuilder and StringBuffer (both in java.lang). StringBuilder and StringBuffer act as String containers where you can create a string, append,insert and update the string.

But, as the doc says StringJoiner is to 'construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.'

So, the methods available only support this purpose. Based on the documentation, the class is not thread-safe.

And, the purpose of this class can actually be achieved in a thread-safe manner since this is like a utility class in util package.

Upvotes: 0

Abhinav
Abhinav

Reputation: 31

Joiner instances are always immutable; a configuration method such as useForNull has no effect on the instance it is invoked on! You must store and use the new joiner instance returned by the method. This makes joiners thread-safe, and safe to store as static final constants.

Checkout this link.

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=2ahUKEwimhb-1mrLdAhUZfd4KHbsfCBAQFjABegQICxAE&url=https%3A%2F%2Fgoogle.github.io%2Fguava%2Freleases%2F19.0%2Fapi%2Fdocs%2Fcom%2Fgoogle%2Fcommon%2Fbase%2FJoiner.html&usg=AOvVaw0iHPRevkI6TS31IUFmBkQc

Upvotes: -4

Related Questions