lucene-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paul Elschot <paul.elsc...@xs4all.nl>
Subject Re: Possible thread safety problem in CachingWrapperFilter
Date Tue, 04 Sep 2007 20:00:17 GMT

On Tuesday 04 September 2007 21:03, Chris Hostetter wrote:
> 
> :     if (cache == null) {
> :       cache = new WeakHashMap();
> :     }
> : 
> : I think the initial snippet is not thread safe and might result
> : in two threads initializing this cache to different objects,
> : possibly conflicting with the cache accesses after that:
> 
> i believe you are write ... if Thread A evaluates the "if (cache == null)" 
> op and then Thread B is given priority and executes the entire method, 
> when Thread A resumes it will blow away the old cache instance (and all of 
> B's hard work)
> 
> I suspect there wasn't a synchro block arround that bit of code because 
> synchronizing on an expression that evaluates to null returns an NPE 
> 
> : Would this be safe to initialize the cache:
> : 
> : synchronized(this) {
> :     if (cache == null) {
> :       cache = new WeakHashMap();
> :     }
> : }
> 
> for the life of me i can't imaging why "cache = new WeakHashMap();" isn't 
> just in the constructor.  then it's garunteed to only execute once.

That would indeed fix the problem.
 
> : and should the cache accesses also use synchronized(this) ?
> 
> I can't see a need for that ... then the same instance couldn't be used on 
> two distinct readers in parallel threads ... but that should be fine.

An alternative fix would be to have two synchronized(this) blocks with
the first one containing the lazy initialisation of the cache.

A patch for this will probably conflict with LUCENE-584 on 
CachingWrapperFilter, so I'd rather not provide a patch myself this time.

Regards,
Paul Elschot

---------------------------------------------------------------------
To unsubscribe, e-mail: java-dev-unsubscribe@lucene.apache.org
For additional commands, e-mail: java-dev-help@lucene.apache.org


Mime
View raw message