[concurrency-interest] Lock free caches

Ernst, Matthias matthias.ernst at coremedia.com
Wed Apr 11 09:04:19 EDT 2007


a technique for memoizing small amounts with a minimum of synchronization
I'm sometimes using is copy-on-write on a plain hashmap:

public class RegexPatternCache
  private static volatile HashMap< String, Pattern > patternCache = new HashMap< String, Pattern >();
     public static Pattern getRegexPattern( String patternString )
         HashMap< String, Pattern > current = patternCache;

         Pattern pattern = current.get(patternString);
         if(pattern == null) {
           Pattern pattern = Pattern.compile( patternString );

           current = new HashMap(patternCache);
           current.put(patternString, pattern);
           patternCache = current;

         return pattern;

A thread that fails to find a pattern compiles it, puts it into a copy of the cache and
writes the cache back. It might override other threads' additions but I assume this
quickly converges.

Synchronization cost: one volatile read and I guess the code path is a little shorter than with a CHM.


matthias.ernst at coremedia.com
software architect
+49.40.32 55 87.503

CoreMedia AG
Executive Board: Sören Stamer (CEO), Dr. Klemens Kleiminger (CFO)
Supervisory Board: Prof. Dr. Joachim Schmidt (Chairman)
Trade Register: Amtsgericht Hamburg, HR B 76277

More information about the Concurrency-interest mailing list