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() / bits.size(), numHashFunctions); 168 } 169 170 /** 171 * @deprecated Use {@link #expectedFpp} instead. 172 */ 173 @Deprecated 174 public double expectedFalsePositiveProbability() { 175 return expectedFpp(); 176 } 177 178 @Override 179 public boolean equals(@Nullable Object object) { 180 if (object == this) { 181 return true; 182 } 183 if (object instanceof BloomFilter) { 184 BloomFilter<?> that = (BloomFilter<?>) object; 185 return this.numHashFunctions == that.numHashFunctions 186 && this.funnel.equals(that.funnel) 187 && this.bits.equals(that.bits) 188 && this.strategy.equals(that.strategy); 189 } 190 return false; 191 } 192 193 @Override 194 public int hashCode() { 195 return Objects.hashCode(numHashFunctions, funnel, strategy, bits); 196 } 197 198 /** 199 * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number 200 * of insertions and expected false positive probability. 201 * 202 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements 203 * than specified, will result in its saturation, and a sharp deterioration of its 204 * false positive probability. 205 * 206 * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided 207 * {@code Funnel<T>} is. 208 * 209 * <p>It is recommended the funnel is implemented as a Java enum. This has the benefit of ensuring 210 * proper serialization and deserialization, which is important since {@link #equals} also relies 211 * on object identity of funnels. 212 * 213 * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use 214 * @param expectedInsertions the number of expected insertions to the constructed 215 * {@code BloomFilter<T>}; must be positive 216 * @param fpp the desired false positive probability (must be positive and less than 1.0) 217 * @return a {@code BloomFilter} 218 */ 219 public static <T> BloomFilter<T> create( 220 Funnel<T> funnel, int expectedInsertions /* n */, double fpp) { 221 checkNotNull(funnel); 222 checkArgument(expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", 223 expectedInsertions); 224 checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); 225 checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); 226 if (expectedInsertions == 0) { 227 expectedInsertions = 1; 228 } 229 /* 230 * TODO(user): Put a warning in the javadoc about tiny fpp values, 231 * since the resulting size is proportional to -log(p), but there is not 232 * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680 233 * which is less that 10kb. Who cares! 234 */ 235 long numBits = optimalNumOfBits(expectedInsertions, fpp); 236 int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); 237 try { 238 return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, 239 BloomFilterStrategies.MURMUR128_MITZ_32); 240 } catch (IllegalArgumentException e) { 241 throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); 242 } 243 } 244 245 /** 246 * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number 247 * of insertions, and a default expected false positive probability of 3%. 248 * 249 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements 250 * than specified, will result in its saturation, and a sharp deterioration of its 251 * false positive probability. 252 * 253 * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided 254 * {@code Funnel<T>} is. 255 * 256 * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use 257 * @param expectedInsertions the number of expected insertions to the constructed 258 * {@code BloomFilter<T>}; must be positive 259 * @return a {@code BloomFilter} 260 */ 261 public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) { 262 return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions 263 } 264 265 /* 266 * Cheat sheet: 267 * 268 * m: total bits 269 * n: expected insertions 270 * b: m/n, bits per insertion 271 272 * p: expected false positive probability 273 * 274 * 1) Optimal k = b * ln2 275 * 2) p = (1 - e ^ (-kn/m))^k 276 * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b 277 * 4) For optimal k: m = -nlnp / ((ln2) ^ 2) 278 */ 279 280 /** 281 * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the 282 * expected insertions and total number of bits in the Bloom filter. 283 * 284 * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. 285 * 286 * @param n expected insertions (must be positive) 287 * @param m total number of bits in Bloom filter (must be positive) 288 */ 289 @VisibleForTesting 290 static int optimalNumOfHashFunctions(long n, long m) { 291 return Math.max(1, (int) Math.round(m / n * Math.log(2))); 292 } 293 294 /** 295 * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified 296 * expected insertions, the required false positive probability. 297 * 298 * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula. 299 * 300 * @param n expected insertions (must be positive) 301 * @param p false positive rate (must be 0 < p < 1) 302 */ 303 @VisibleForTesting 304 static long optimalNumOfBits(long n, double p) { 305 if (p == 0) { 306 p = Double.MIN_VALUE; 307 } 308 return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); 309 } 310 311 private Object writeReplace() { 312 return new SerialForm<T>(this); 313 } 314 315 private static class SerialForm<T> implements Serializable { 316 final long[] data; 317 final int numHashFunctions; 318 final Funnel<T> funnel; 319 final Strategy strategy; 320 321 SerialForm(BloomFilter<T> bf) { 322 this.data = bf.bits.data; 323 this.numHashFunctions = bf.numHashFunctions; 324 this.funnel = bf.funnel; 325 this.strategy = bf.strategy; 326 } 327 Object readResolve() { 328 return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); 329 } 330 private static final long serialVersionUID = 1; 331 } 332}