Is a non-synchronized WeakHashMap harmful?

635 Views Asked by At

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?

2

There are 2 best solutions below

0
Basil Bourque On BEST ANSWER

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.

3
Tom Hawtin - tackline On

Multi-threaded use of HashMaps can lead to infinite loops. IIRC, concurrent rehashing can leave buckets forming a chain.

Generally, avoid anything with a race condition. There are exceptions, for instance, immutable cache values.

Also:

Types that represent a value, such as String, are not a good type to use as a key to a WeakHashMap.

Lazy initialisation, beyond that which the JVM provides for free, is often not worth it. In this case, it doesn't particularly matter the you may end up with two maps.