synchronized void putIfAbsent(Query query, LeafReaderContext context, DocIdSet set) { // under a lock to make sure that mostRecentlyUsedQueries and cache remain sync'ed // we don't want to have user-provided queries as keys in our cache since queries are mutable assert query instanceof BoostQuery == false; assert query instanceof ConstantScoreQuery == false; Query singleton = uniqueQueries.putIfAbsent(query, query); if (singleton == null) { onQueryCache(singleton, LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + ramBytesUsed(query)); } else { query = singleton; } final Object key = context.reader().getCoreCacheKey(); LeafCache leafCache = cache.get(key); if (leafCache == null) { leafCache = new LeafCache(key); final LeafCache previous = cache.put(context.reader().getCoreCacheKey(), leafCache); ramBytesUsed += HASHTABLE_RAM_BYTES_PER_ENTRY; assert previous == null; // we just created a new leaf cache, need to register a close listener context .reader() .addCoreClosedListener( new CoreClosedListener() { @Override public void onClose(Object ownerCoreCacheKey) { clearCoreCacheKey(ownerCoreCacheKey); } }); } leafCache.putIfAbsent(query, set); evictIfNecessary(); }
synchronized DocIdSet get(Query key, LeafReaderContext context) { assert key instanceof BoostQuery == false; assert key instanceof ConstantScoreQuery == false; final Object readerKey = context.reader().getCoreCacheKey(); final LeafCache leafCache = cache.get(readerKey); if (leafCache == null) { onMiss(readerKey, key); return null; } // this get call moves the query to the most-recently-used position final Query singleton = uniqueQueries.get(key); if (singleton == null) { onMiss(readerKey, key); return null; } final DocIdSet cached = leafCache.get(singleton); if (cached == null) { onMiss(readerKey, singleton); } else { onHit(readerKey, singleton); } return cached; }
private void onEviction(Query singleton) { onQueryEviction(singleton, LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + ramBytesUsed(singleton)); for (LeafCache leafCache : cache.values()) { leafCache.remove(singleton); } }