Reputation: 133
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
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
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
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
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.
Upvotes: -4