6

I have a web application where users submit queries to a Lucene index. The queries are parsed by a Lucene QueryParser. I learned the hard way that QueryParser is not thread-safe.

Is it better to use a single QueryParser instance, and synchronize on calls to its parse() method? Or is it better to construct a new instance for each query? (Or would I be better served by a pool of QueryParsers?)

I know that in general questions like this depend on the particulars and require profiling, but maybe someone out there can say definitively "QueryParsers are extremely inexpensive/expensive to construct"?

Robert Tupelo-Schneck
  • 10,047
  • 4
  • 47
  • 58

1 Answers1

6

Create a new one each time. These are lightweight objects and the JVM handles object creation and garbage collection very well. Definitely do not use an object pool.

Joel
  • 29,538
  • 35
  • 110
  • 138
  • +1 yes, definitely no reason to pool (or share a single) `QueryParser` object. Further reading: [Java theory and practice: Urban performance legends, revisited](http://www.ibm.com/developerworks/java/library/j-jtp09275/index.html) – WhiteFang34 Apr 02 '11 at 22:22
  • Thanks! @WhiteFang34, that link is about the low cost of allocation in general, but it's surely worth pointing that there **are** some types of objects where construction is not cheap because a lot of work is done beyond the allocation itself. In the Lucene world one is often reminded to share a single `IndexSearcher` for performance reasons. – Robert Tupelo-Schneck Apr 04 '11 at 14:48