I need to replace some characters in a string: Each DOT to Underscore.
Simply do: myString.replace(".","_");
which works.
However, I want to use CharMatcher
from Guava, which supposed to have better performance.
CharMatcher dotCharMatcher = CharMatcher.anyOf(".");
dotCharMatcher.replaceFrom(myString, "_");
It runs on a sever with many threads.
Can I make dotCharMatcher
a static field in the class that uses it, or should I create one in each request? (is it thread safe?)
Thanks
Thread SafetyStatic variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.
net but in java static fields are not threadsafer than any other type of field. You have it backwards. Because static fields and methods are likely to be accessed from multiple threads, it is a good programming practice to do the work to ensure that they are threadsafe.
Yes, by inspection of CharMatcher.java
, the instance returned from anyOf
is thread-safe.
However, the Guava's string utilities, explained documentation specifically says that Joiner
and Splitter
are thread-safe but doesn't make the same claim for CharMatcher
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With