001 /* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015 package com.google.common.hash; 016 017 import static com.google.common.base.Preconditions.checkArgument; 018 import static com.google.common.base.Preconditions.checkNotNull; 019 020 import com.google.common.annotations.Beta; 021 import com.google.common.annotations.VisibleForTesting; 022 import com.google.common.base.Preconditions; 023 import com.google.common.hash.BloomFilterStrategies.BitArray; 024 025 import java.io.Serializable; 026 027 /** 028 * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test 029 * with one-sided error: if it claims that an element is contained in it, this might be in error, 030 * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. 031 * 032 * <p>If you are unfamiliar with Bloom filters, this nice 033 * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand 034 * how they work. 035 * 036 * 037 * @param <T> the type of instances that the {@code BloomFilter} accepts 038 * @author Dimitris Andreou 039 * @author Kevin Bourrillion 040 * @since 11.0 041 */ 042 @Beta 043 public final class BloomFilter<T> implements Serializable { 044 /** 045 * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. 046 * 047 * <p>Implementations should be collections of pure functions (i.e. stateless). 048 */ 049 interface Strategy extends java.io.Serializable { 050 051 /** 052 * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. 053 * 054 * <p>Returns whether any bits changed as a result of this operation. 055 */ 056 <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); 057 058 /** 059 * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; 060 * returns {@code true} if and only if all selected bits are set. 061 */ 062 <T> boolean mightContain( 063 T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); 064 065 /** 066 * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. 067 * Only values in the [-128, 127] range are valid for the compact serial form. 068 * Non-negative values are reserved for enums defined in BloomFilterStrategies; 069 * negative values are reserved for any custom, stateful strategy we may define 070 * (e.g. any kind of strategy that would depend on user input). 071 */ 072 int ordinal(); 073 } 074 075 /** The bit set of the BloomFilter (not necessarily power of 2!)*/ 076 private final BitArray bits; 077 078 /** Number of hashes per element */ 079 private final int numHashFunctions; 080 081 /** The funnel to translate Ts to bytes */ 082 private final Funnel<T> funnel; 083 084 /** 085 * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. 086 */ 087 private final Strategy strategy; 088 089 /** 090 * Creates a BloomFilter. 091 */ 092 private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel, 093 Strategy strategy) { 094 Preconditions.checkArgument(numHashFunctions > 0, "numHashFunctions zero or negative"); 095 this.bits = checkNotNull(bits); 096 this.numHashFunctions = numHashFunctions; 097 this.funnel = checkNotNull(funnel); 098 this.strategy = strategy; 099 100 /* 101 * This only exists to forbid BFs that cannot use the compact persistent representation. 102 * If it ever throws, at a user who was not intending to use that representation, we should 103 * reconsider 104 */ 105 if (numHashFunctions > 255) { 106 throw new AssertionError("Currently we don't allow BloomFilters that would use more than" + 107 "255 hash functions, please contact the guava team"); 108 } 109 } 110 111 /** 112 * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to 113 * this instance but shares no mutable state. 114 * 115 * @since 12.0 116 */ 117 public BloomFilter<T> copy() { 118 return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy); 119 } 120 121 /** 122 * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, 123 * {@code false} if this is <i>definitely</i> not the case. 124 */ 125 public boolean mightContain(T object) { 126 return strategy.mightContain(object, funnel, numHashFunctions, bits); 127 } 128 129 /** 130 * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of 131 * {@link #mightContain(Object)} with the same element will always return {@code true}. 132 * 133 * @return true if the bloom filter's bits changed as a result of this operation. If the bits 134 * changed, this is <i>definitely</i> the first time {@code object} has been added to the 135 * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} 136 * has been added to the filter. Note that {@code put(t)} always returns the 137 * <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time 138 * it is called." 139 * @since 12.0 (present in 11.0 with {@code void} return type}) 140 */ 141 public boolean put(T object) { 142 return strategy.put(object, funnel, numHashFunctions, bits); 143 } 144 145 /** 146 * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return 147 * {@code true} for an object that has not actually been put in the {@code BloomFilter}. 148 * 149 * <p>Ideally, this number should be close to the {@code falsePositiveProbability} parameter 150 * passed in {@linkplain #create(Funnel, int, double)}, or smaller. If it is 151 * significantly higher, it is usually the case that too many elements (more than 152 * expected) have been put in the {@code BloomFilter}, degenerating it. 153 */ 154 public double expectedFalsePositiveProbability() { 155 return Math.pow((double) bits.bitCount() / bits.size(), numHashFunctions); 156 } 157 158 /** 159 * {@inheritDoc} 160 * 161 * <p>This implementation uses reference equality to compare funnels. 162 */ 163 @Override public boolean equals(Object o) { 164 if (o instanceof BloomFilter) { 165 BloomFilter<?> that = (BloomFilter<?>) o; 166 return this.numHashFunctions == that.numHashFunctions 167 && this.bits.equals(that.bits) 168 && this.funnel == that.funnel 169 && this.strategy == that.strategy; 170 } 171 return false; 172 } 173 174 @Override public int hashCode() { 175 return bits.hashCode(); 176 } 177 178 @VisibleForTesting int getHashCount() { 179 return numHashFunctions; 180 } 181 182 /** 183 * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number 184 * of insertions and expected false positive probability. 185 * 186 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements 187 * than specified, will result in its saturation, and a sharp deterioration of its 188 * false positive probability. 189 * 190 * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided 191 * {@code Funnel<T>} is. 192 * 193 * <p>It is recommended the funnel is implemented as a Java enum. This has the benefit of ensuring 194 * proper serialization and deserialization, which is important since {@link #equals} also relies 195 * on object identity of funnels. 196 * 197 * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use 198 * @param expectedInsertions the number of expected insertions to the constructed 199 * {@code BloomFilter<T>}; must be positive 200 * @param falsePositiveProbability the desired false positive probability (must be positive and 201 * less than 1.0) 202 * @return a {@code BloomFilter} 203 */ 204 public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */, 205 double falsePositiveProbability) { 206 checkNotNull(funnel); 207 checkArgument(expectedInsertions >= 0, "Expected insertions cannot be negative"); 208 checkArgument(falsePositiveProbability > 0.0 & falsePositiveProbability < 1.0, 209 "False positive probability in (0.0, 1.0)"); 210 if (expectedInsertions == 0) { 211 expectedInsertions = 1; 212 } 213 /* 214 * andreou: I wanted to put a warning in the javadoc about tiny fpp values, 215 * since the resulting size is proportional to -log(p), but there is not 216 * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680 217 * which is less that 10kb. Who cares! 218 */ 219 int numBits = optimalNumOfBits(expectedInsertions, falsePositiveProbability); 220 int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); 221 return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, 222 BloomFilterStrategies.MURMUR128_MITZ_32); 223 } 224 225 /** 226 * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number 227 * of insertions, and a default expected false positive probability of 3%. 228 * 229 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements 230 * than specified, will result in its saturation, and a sharp deterioration of its 231 * false positive probability. 232 * 233 * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided 234 * {@code Funnel<T>} is. 235 * 236 * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use 237 * @param expectedInsertions the number of expected insertions to the constructed 238 * {@code BloomFilter<T>}; must be positive 239 * @return a {@code BloomFilter} 240 */ 241 public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) { 242 return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions 243 } 244 245 /* 246 * Cheat sheet: 247 * 248 * m: total bits 249 * n: expected insertions 250 * b: m/n, bits per insertion 251 252 * p: expected false positive probability 253 * 254 * 1) Optimal k = b * ln2 255 * 2) p = (1 - e ^ (-kn/m))^k 256 * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b 257 * 4) For optimal k: m = -nlnp / ((ln2) ^ 2) 258 */ 259 260 private static final double LN2 = Math.log(2); 261 private static final double LN2_SQUARED = LN2 * LN2; 262 263 /** 264 * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the 265 * expected insertions and total number of bits in the Bloom filter. 266 * 267 * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. 268 * 269 * @param n expected insertions (must be positive) 270 * @param m total number of bits in Bloom filter (must be positive) 271 */ 272 @VisibleForTesting static int optimalNumOfHashFunctions(int n, int m) { 273 return Math.max(1, (int) Math.round(m / n * LN2)); 274 } 275 276 /** 277 * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified 278 * expected insertions, the required false positive probability. 279 * 280 * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula. 281 * 282 * @param n expected insertions (must be positive) 283 * @param p false positive rate (must be 0 < p < 1) 284 */ 285 @VisibleForTesting static int optimalNumOfBits(int n, double p) { 286 return (int) (-n * Math.log(p) / LN2_SQUARED); 287 } 288 289 private Object writeReplace() { 290 return new SerialForm<T>(this); 291 } 292 293 private static class SerialForm<T> implements Serializable { 294 final long[] data; 295 final int numHashFunctions; 296 final Funnel<T> funnel; 297 final Strategy strategy; 298 299 SerialForm(BloomFilter<T> bf) { 300 this.data = bf.bits.data; 301 this.numHashFunctions = bf.numHashFunctions; 302 this.funnel = bf.funnel; 303 this.strategy = bf.strategy; 304 } 305 Object readResolve() { 306 return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); 307 } 308 private static final long serialVersionUID = 1; 309 } 310 }