I have a code look like this.
private static Map<String, Pattern> PATTERNS;
private static Map<String, Pattern> patterns() {
if (PATTERNS == null) {
PATTERNS = new WeakHashMap<>(); // ok? or should be synchronized?
}
return PATTERNS;
}
// intending to reuse those pre-compiled patters
private static Pattern pattern(final String regex) {
return patterns().computeIfAbsent(
requireNonNull(regex, "regex is null"), Pattern::compile);
}
I already know the WeakHashMap
is not synchronized. I just don't care about multiple construction of Pattern
s.
Should the PATTERNS
be synchronized, in case of multi-threaded environment?
Is a non-synchronized WeakHashMap harmful?
Yes. You must add additional protection to use WeakHashMap
across threads.
Thus the suggestion found in the class Javadoc:
A synchronized
WeakHashMap
may be constructed using theCollections.synchronizedMap
method
PATTERNS = Collections.synchronizedMap(new WeakHashMap<>())
See this Question.