[concurrency-interest] Lock free caches

Mike Quilleash mike.quilleash at subexazure.com
Wed Apr 11 04:53:48 EDT 2007

Hi all,
I have a performance bottleneck in my code involving
java.util.regex.Pattern.  Doing Pattern.compile() is slow and I would
like to cache these across the application (as the pool of used patterns
is quite small but used regularly), but I want to keep any
synchronization to a minimum.
I thought about the following which just does a simple check if present
and build and insert if not.
public class RegexPatternCache
    private static ConcurrentMap< String, Pattern > patternCache = new
ConcurrentHashMap< String, Pattern >();
    public static Pattern getRegexPattern( String patternString )
        if ( patternCache.containsKey( patternString ) )
            return patternCache.get( patternString );
        Pattern pattern = Pattern.compile( patternString );
        patternCache.putIfAbsent( patternString, pattern );
        return pattern;

I believe the above is threadsafe (please correct me if not!), worst
case being two threads may call getRegexPattern at the same time with
the same patternString and both compile the pattern.  As this is a
deterministic operation I don't see any problem with this.  Is this the
best way of implementing this sort of mini-cache?  Is there an
established best-practice/pattern for this sort of thing?

 This e-mail is bound by the terms and conditions described at http://www.subexazure.com/mail-disclaimer.html

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20070411/5e48d44f/attachment-0001.html 

More information about the Concurrency-interest mailing list