javathread-safetyconcurrentmodificationweakhashmap

Is a non-synchronized WeakHashMap harmful?


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?


Solution

  • 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.synchronizedMap(new WeakHashMap<>())
    

    See this Question.