Is a non-synchronized WeakHashMap harmful?

Jin Kwon :

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

Should the PATTERNS be synchronized, in case of multi-threaded environment?

Basil Bourque :

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 the Collections.synchronizedMap method

PATTERNS = Collections.synchronized( new WeakHashMap<>() ) ;

See this Question.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130356&siteId=1