KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lucene > search > CachingWrapperFilter


1 package org.apache.lucene.search;
2
3 /**
4  * Copyright 2004 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import org.apache.lucene.index.IndexReader;
20 import java.util.BitSet JavaDoc;
21 import java.util.WeakHashMap JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.io.IOException JavaDoc;
24
25 /**
26  * Wraps another filter's result and caches it. The caching
27  * behavior is like {@link QueryFilter}. The purpose is to allow
28  * filters to simply filter, and then wrap with this class to add
29  * caching, keeping the two concerns decoupled yet composable.
30  */

31 public class CachingWrapperFilter extends Filter {
32   private Filter filter;
33
34   /**
35    * @todo What about serialization in RemoteSearchable? Caching won't work.
36    * Should transient be removed?
37    */

38   private transient Map JavaDoc cache;
39
40   /**
41    * @param filter Filter to cache results of
42    */

43   public CachingWrapperFilter(Filter filter) {
44     this.filter = filter;
45   }
46
47   public BitSet JavaDoc bits(IndexReader reader) throws IOException JavaDoc {
48     if (cache == null) {
49       cache = new WeakHashMap JavaDoc();
50     }
51
52     synchronized (cache) { // check cache
53
BitSet JavaDoc cached = (BitSet JavaDoc) cache.get(reader);
54       if (cached != null) {
55         return cached;
56       }
57     }
58
59     final BitSet JavaDoc bits = filter.bits(reader);
60
61     synchronized (cache) { // update cache
62
cache.put(reader, bits);
63     }
64
65     return bits;
66   }
67
68   public String JavaDoc toString() {
69     return "CachingWrapperFilter("+filter+")";
70   }
71
72   public boolean equals(Object JavaDoc o) {
73     if (!(o instanceof CachingWrapperFilter)) return false;
74     return this.filter.equals(((CachingWrapperFilter)o).filter);
75   }
76
77   public int hashCode() {
78     return filter.hashCode() ^ 0x1117BF25;
79   }
80 }
81
Popular Tags