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 015package com.google.common.hash; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019 020import com.google.common.annotations.Beta; 021import com.google.common.annotations.VisibleForTesting; 022import com.google.common.base.Objects; 023import com.google.common.base.Predicate; 024import com.google.common.hash.BloomFilterStrategies.BitArray; 025 026import java.io.Serializable; 027 028import javax.annotation.Nullable; 029 030/** 031 * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test 032 * with one-sided error: if it claims that an element is contained in it, this might be in error, 033 * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. 034 * 035 * <p>If you are unfamiliar with Bloom filters, this nice 036 * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand 037 * how they work. 038 * 039 * <p>The false positive probability ({@code FPP}) of a bloom filter is defined as the probability 040 * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that 041 * has not actually been put in the {@code BloomFilter}. 042 * 043 * 044 * @param <T> the type of instances that the {@code BloomFilter} accepts 045 * @author Dimitris Andreou 046 * @author Kevin Bourrillion 047 * @since 11.0 048 */ 049@Beta 050public final class BloomFilter<T> implements Predicate<T>, Serializable { 051 /** 052 * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. 053 * 054 * <p>Implementations should be collections of pure functions (i.e. stateless). 055 */ 056 interface Strategy extends java.io.Serializable { 057 058 /** 059 * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. 060 * 061 * <p>Returns whether any bits changed as a result of this operation. 062 */ 063 <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); 064 065 /** 066 * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; 067 * returns {@code true} if and only if all selected bits are set. 068 */ 069 <T> boolean mightContain( 070 T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); 071 072 /** 073 * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. 074 * Only values in the [-128, 127] range are valid for the compact serial form. 075 * Non-negative values are reserved for enums defined in BloomFilterStrategies; 076 * negative values are reserved for any custom, stateful strategy we may define 077 * (e.g. any kind of strategy that would depend on user input). 078 */ 079 int ordinal(); 080 } 081 082 /** The bit set of the BloomFilter (not necessarily power of 2!)*/ 083 private final BitArray bits; 084 085 /** Number of hashes per element */ 086 private final int numHashFunctions; 087 088 /** The funnel to translate Ts to bytes */ 089 private final Funnel<T> funnel; 090 091 /** 092 * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. 093 */ 094 private final Strategy strategy; 095 096 /** 097 * Creates a BloomFilter. 098 */ 099 private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel, 100 Strategy strategy) { 101 checkArgument(numHashFunctions > 0, 102 "numHashFunctions (%s) must be > 0", numHashFunctions); 103 checkArgument(numHashFunctions <= 255, 104 "numHashFunctions (%s) must be <= 255", numHashFunctions); 105 this.bits = checkNotNull(bits); 106 this.numHashFunctions = numHashFunctions; 107 this.funnel = checkNotNull(funnel); 108 this.strategy = checkNotNull(strategy); 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 * Equivalent to {@link #mightContain}; provided only to satisfy the {@link Predicate} interface. 131 * When using a reference of type {@code BloomFilter}, always invoke {@link #mightContain} 132 * directly instead. 133 */ 134 @Override public boolean apply(T input) { 135 return mightContain(input); 136 } 137 138 /** 139 * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of 140 * {@link #mightContain(Object)} with the same element will always return {@code true}. 141 * 142 * @return true if the bloom filter's bits changed as a result of this operation. If the bits 143 * changed, this is <i>definitely</i> the first time {@code object} has been added to the 144 * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} 145 * has been added to the filter. Note that {@code put(t)} always returns the 146 * <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time 147 * it is called." 148 * @since 12.0 (present in 11.0 with {@code void} return type}) 149 */ 150 public boolean put(T object) { 151 return strategy.put(object, funnel, numHashFunctions, bits); 152 } 153 154 /** 155 * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return 156 * {@code true} for an object that has not actually been put in the {@code BloomFilter}. 157 * 158 * <p>Ideally, this number should be close to the {@code fpp} parameter 159 * passed in {@linkplain #create(Funnel, int, double)}, or smaller. If it is 160 * significantly higher, it is usually the case that too many elements (more than 161 * expected) have been put in the {@code BloomFilter}, degenerating it. 162 * 163 * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) 164 */ 165 public double expectedFpp() { 166 // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last homie!) 167 return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); 168 } 169 170 /** 171 * Returns the number of bits in the underlying bit array. 172 */ 173 @VisibleForTesting long bitSize() { 174 return bits.bitSize(); 175 } 176 177 /** 178 * Determines whether a given bloom filter is compatible with this bloom filter. For two 179 * bloom filters to be compatible, they must: 180 * 181 * <ul> 182 * <li>not be the same instance 183 * <li>have the same number of hash functions 184 * <li>have the same bit size 185 * <li>have the same strategy 186 * <li>have equal funnels 187 * <ul> 188 * 189 * @param that The bloom filter to check for compatibility. 190 * @since 15.0 191 */ 192 public boolean isCompatible(BloomFilter<T> that) { 193 checkNotNull(that); 194 return (this != that) && 195 (this.numHashFunctions == that.numHashFunctions) && 196 (this.bitSize() == that.bitSize()) && 197 (this.strategy.equals(that.strategy)) && 198 (this.funnel.equals(that.funnel)); 199 } 200 201 /** 202 * Combines this bloom filter with another bloom filter by performing a bitwise OR of the 203 * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the 204 * bloom filters are appropriately sized to avoid saturating them. 205 * 206 * @param that The bloom filter to combine this bloom filter with. It is not mutated. 207 * @throws IllegalArgumentException if {@code isCompatible(that) == false} 208 * 209 * @since 15.0 210 */ 211 public void putAll(BloomFilter<T> that) { 212 checkNotNull(that); 213 checkArgument(this != that, "Cannot combine a BloomFilter with itself."); 214 checkArgument(this.numHashFunctions == that.numHashFunctions, 215 "BloomFilters must have the same number of hash functions (%s != %s)", 216 this.numHashFunctions, that.numHashFunctions); 217 checkArgument(this.bitSize() == that.bitSize(), 218 "BloomFilters must have the same size underlying bit arrays (%s != %s)", 219 this.bitSize(), that.bitSize()); 220 checkArgument(this.strategy.equals(that.strategy), 221 "BloomFilters must have equal strategies (%s != %s)", 222 this.strategy, that.strategy); 223 checkArgument(this.funnel.equals(that.funnel), 224 "BloomFilters must have equal funnels (%s != %s)", 225 this.funnel, that.funnel); 226 this.bits.putAll(that.bits); 227 } 228 229 @Override 230 public boolean equals(@Nullable Object object) { 231 if (object == this) { 232 return true; 233 } 234 if (object instanceof BloomFilter) { 235 BloomFilter<?> that = (BloomFilter<?>) object; 236 return this.numHashFunctions == that.numHashFunctions 237 && this.funnel.equals(that.funnel) 238 && this.bits.equals(that.bits) 239 && this.strategy.equals(that.strategy); 240 } 241 return false; 242 } 243 244 @Override 245 public int hashCode() { 246 return Objects.hashCode(numHashFunctions, funnel, strategy, bits); 247 } 248 249 /** 250 * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of 251 * insertions and expected false positive probability. 252 * 253 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements 254 * than specified, will result in its saturation, and a sharp deterioration of its 255 * false positive probability. 256 * 257 * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided 258 * {@code Funnel<T>} is. 259 * 260 * <p>It is recommended that the funnel be implemented as a Java enum. This has the 261 * benefit of ensuring proper serialization and deserialization, which is important 262 * since {@link #equals} also relies on object identity of funnels. 263 * 264 * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use 265 * @param expectedInsertions the number of expected insertions to the constructed 266 * {@code BloomFilter<T>}; must be positive 267 * @param fpp the desired false positive probability (must be positive and less than 1.0) 268 * @return a {@code BloomFilter} 269 */ 270 public static <T> BloomFilter<T> create( 271 Funnel<T> funnel, int expectedInsertions /* n */, double fpp) { 272 checkNotNull(funnel); 273 checkArgument(expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", 274 expectedInsertions); 275 checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); 276 checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); 277 if (expectedInsertions == 0) { 278 expectedInsertions = 1; 279 } 280 /* 281 * TODO(user): Put a warning in the javadoc about tiny fpp values, 282 * since the resulting size is proportional to -log(p), but there is not 283 * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680 284 * which is less than 10kb. Who cares! 285 */ 286 long numBits = optimalNumOfBits(expectedInsertions, fpp); 287 int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); 288 try { 289 return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, 290 BloomFilterStrategies.MURMUR128_MITZ_32); 291 } catch (IllegalArgumentException e) { 292 throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); 293 } 294 } 295 296 /** 297 * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of 298 * insertions and a default expected false positive probability of 3%. 299 * 300 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements 301 * than specified, will result in its saturation, and a sharp deterioration of its 302 * false positive probability. 303 * 304 * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided 305 * {@code Funnel<T>} is. 306 * 307 * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use 308 * @param expectedInsertions the number of expected insertions to the constructed 309 * {@code BloomFilter<T>}; must be positive 310 * @return a {@code BloomFilter} 311 */ 312 public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) { 313 return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions 314 } 315 316 /* 317 * Cheat sheet: 318 * 319 * m: total bits 320 * n: expected insertions 321 * b: m/n, bits per insertion 322 * p: expected false positive probability 323 * 324 * 1) Optimal k = b * ln2 325 * 2) p = (1 - e ^ (-kn/m))^k 326 * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b 327 * 4) For optimal k: m = -nlnp / ((ln2) ^ 2) 328 */ 329 330 /** 331 * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the 332 * expected insertions and total number of bits in the Bloom filter. 333 * 334 * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. 335 * 336 * @param n expected insertions (must be positive) 337 * @param m total number of bits in Bloom filter (must be positive) 338 */ 339 @VisibleForTesting 340 static int optimalNumOfHashFunctions(long n, long m) { 341 return Math.max(1, (int) Math.round(m / n * Math.log(2))); 342 } 343 344 /** 345 * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified 346 * expected insertions, the required false positive probability. 347 * 348 * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula. 349 * 350 * @param n expected insertions (must be positive) 351 * @param p false positive rate (must be 0 < p < 1) 352 */ 353 @VisibleForTesting 354 static long optimalNumOfBits(long n, double p) { 355 if (p == 0) { 356 p = Double.MIN_VALUE; 357 } 358 return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); 359 } 360 361 private Object writeReplace() { 362 return new SerialForm<T>(this); 363 } 364 365 private static class SerialForm<T> implements Serializable { 366 final long[] data; 367 final int numHashFunctions; 368 final Funnel<T> funnel; 369 final Strategy strategy; 370 371 SerialForm(BloomFilter<T> bf) { 372 this.data = bf.bits.data; 373 this.numHashFunctions = bf.numHashFunctions; 374 this.funnel = bf.funnel; 375 this.strategy = bf.strategy; 376 } 377 Object readResolve() { 378 return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); 379 } 380 private static final long serialVersionUID = 1; 381 } 382}