Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use Guava CharMatcher as a static fields in a class . Is CharMatcher thread safe?

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

like image 776
Eyal Golan Avatar asked Nov 05 '14 13:11

Eyal Golan


People also ask

Are static fields thread safe?

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.

Is static field thread safe in Java?

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.


1 Answers

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.

like image 198
Joe Avatar answered Oct 02 '22 14:10

Joe