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.LockFreeBitArray; 025import com.google.common.math.DoubleMath; 026import com.google.common.primitives.SignedBytes; 027import com.google.common.primitives.UnsignedBytes; 028import com.google.errorprone.annotations.CanIgnoreReturnValue; 029import java.io.DataInputStream; 030import java.io.DataOutputStream; 031import java.io.IOException; 032import java.io.InputStream; 033import java.io.OutputStream; 034import java.io.Serializable; 035import java.math.RoundingMode; 036import java.util.stream.Collector; 037import org.checkerframework.checker.nullness.qual.Nullable; 038 039/** 040 * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test 041 * with one-sided error: if it claims that an element is contained in it, this might be in error, 042 * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. 043 * 044 * <p>If you are unfamiliar with Bloom filters, this nice <a 045 * href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand how 046 * they work. 047 * 048 * <p>The false positive probability ({@code FPP}) of a Bloom filter is defined as the probability 049 * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that 050 * has not actually been put in the {@code BloomFilter}. 051 * 052 * <p>Bloom filters are serializable. They also support a more compact serial representation via the 053 * {@link #writeTo} and {@link #readFrom} methods. Both serialized forms will continue to be 054 * supported by future versions of this library. However, serial forms generated by newer versions 055 * of the code may not be readable by older versions of the code (e.g., a serialized Bloom filter 056 * generated today may <i>not</i> be readable by a binary that was compiled 6 months ago). 057 * 058 * <p>As of Guava 23.0, this class is thread-safe and lock-free. It internally uses atomics and 059 * compare-and-swap to ensure correctness when multiple threads are used to access it. 060 * 061 * @param <T> the type of instances that the {@code BloomFilter} accepts 062 * @author Dimitris Andreou 063 * @author Kevin Bourrillion 064 * @since 11.0 (thread-safe since 23.0) 065 */ 066@Beta 067public final class BloomFilter<T> implements Predicate<T>, Serializable { 068 /** 069 * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. 070 * 071 * <p>Implementations should be collections of pure functions (i.e. stateless). 072 */ 073 interface Strategy extends java.io.Serializable { 074 075 /** 076 * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. 077 * 078 * <p>Returns whether any bits changed as a result of this operation. 079 */ 080 <T> boolean put( 081 T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); 082 083 /** 084 * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; 085 * returns {@code true} if and only if all selected bits are set. 086 */ 087 <T> boolean mightContain( 088 T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); 089 090 /** 091 * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. Only 092 * values in the [-128, 127] range are valid for the compact serial form. Non-negative values 093 * are reserved for enums defined in BloomFilterStrategies; negative values are reserved for any 094 * custom, stateful strategy we may define (e.g. any kind of strategy that would depend on user 095 * input). 096 */ 097 int ordinal(); 098 } 099 100 /** The bit set of the BloomFilter (not necessarily power of 2!) */ 101 private final LockFreeBitArray bits; 102 103 /** Number of hashes per element */ 104 private final int numHashFunctions; 105 106 /** The funnel to translate Ts to bytes */ 107 private final Funnel<? super T> funnel; 108 109 /** The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ 110 private final Strategy strategy; 111 112 /** Creates a BloomFilter. */ 113 private BloomFilter( 114 LockFreeBitArray bits, int numHashFunctions, Funnel<? super T> funnel, Strategy strategy) { 115 checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); 116 checkArgument( 117 numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); 118 this.bits = checkNotNull(bits); 119 this.numHashFunctions = numHashFunctions; 120 this.funnel = checkNotNull(funnel); 121 this.strategy = checkNotNull(strategy); 122 } 123 124 /** 125 * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to 126 * this instance but shares no mutable state. 127 * 128 * @since 12.0 129 */ 130 public BloomFilter<T> copy() { 131 return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy); 132 } 133 134 /** 135 * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, {@code 136 * false} if this is <i>definitely</i> not the case. 137 */ 138 public boolean mightContain(T object) { 139 return strategy.mightContain(object, funnel, numHashFunctions, bits); 140 } 141 142 /** 143 * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain} 144 * instead. 145 */ 146 @Deprecated 147 @Override 148 public boolean apply(T input) { 149 return mightContain(input); 150 } 151 152 /** 153 * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of {@link 154 * #mightContain(Object)} with the same element will always return {@code true}. 155 * 156 * @return true if the Bloom filter's bits changed as a result of this operation. If the bits 157 * changed, this is <i>definitely</i> the first time {@code object} has been added to the 158 * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} has 159 * been added to the filter. Note that {@code put(t)} always returns the <i>opposite</i> 160 * result to what {@code mightContain(t)} would have returned at the time it is called. 161 * @since 12.0 (present in 11.0 with {@code void} return type}) 162 */ 163 @CanIgnoreReturnValue 164 public boolean put(T object) { 165 return strategy.put(object, funnel, numHashFunctions, bits); 166 } 167 168 /** 169 * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return {@code 170 * true} for an object that has not actually been put in the {@code BloomFilter}. 171 * 172 * <p>Ideally, this number should be close to the {@code fpp} parameter passed in {@linkplain 173 * #create(Funnel, int, double)}, or smaller. If it is significantly higher, it is usually the 174 * case that too many elements (more than expected) have been put in the {@code BloomFilter}, 175 * degenerating it. 176 * 177 * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) 178 */ 179 public double expectedFpp() { 180 // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last homie!) 181 return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); 182 } 183 184 /** 185 * Returns an estimate for the total number of distinct elements that have been added to this 186 * Bloom filter. This approximation is reasonably accurate if it does not exceed the value of 187 * {@code expectedInsertions} that was used when constructing the filter. 188 * 189 * @since 22.0 190 */ 191 public long approximateElementCount() { 192 long bitSize = bits.bitSize(); 193 long bitCount = bits.bitCount(); 194 195 /** 196 * Each insertion is expected to reduce the # of clear bits by a factor of 197 * `numHashFunctions/bitSize`. So, after n insertions, expected bitCount is `bitSize * (1 - (1 - 198 * numHashFunctions/bitSize)^n)`. Solving that for n, and approximating `ln x` as `x - 1` when x 199 * is close to 1 (why?), gives the following formula. 200 */ 201 double fractionOfBitsSet = (double) bitCount / bitSize; 202 return DoubleMath.roundToLong( 203 -Math.log1p(-fractionOfBitsSet) * bitSize / numHashFunctions, RoundingMode.HALF_UP); 204 } 205 206 /** Returns the number of bits in the underlying bit array. */ 207 @VisibleForTesting 208 long bitSize() { 209 return bits.bitSize(); 210 } 211 212 /** 213 * Determines whether a given Bloom filter is compatible with this Bloom filter. For two Bloom 214 * filters to be compatible, they must: 215 * 216 * <ul> 217 * <li>not be the same instance 218 * <li>have the same number of hash functions 219 * <li>have the same bit size 220 * <li>have the same strategy 221 * <li>have equal funnels 222 * </ul> 223 * 224 * @param that The Bloom filter to check for compatibility. 225 * @since 15.0 226 */ 227 public boolean isCompatible(BloomFilter<T> that) { 228 checkNotNull(that); 229 return this != that 230 && this.numHashFunctions == that.numHashFunctions 231 && this.bitSize() == that.bitSize() 232 && this.strategy.equals(that.strategy) 233 && this.funnel.equals(that.funnel); 234 } 235 236 /** 237 * Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the 238 * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom 239 * filters are appropriately sized to avoid saturating them. 240 * 241 * @param that The Bloom filter to combine this Bloom filter with. It is not mutated. 242 * @throws IllegalArgumentException if {@code isCompatible(that) == false} 243 * @since 15.0 244 */ 245 public void putAll(BloomFilter<T> that) { 246 checkNotNull(that); 247 checkArgument(this != that, "Cannot combine a BloomFilter with itself."); 248 checkArgument( 249 this.numHashFunctions == that.numHashFunctions, 250 "BloomFilters must have the same number of hash functions (%s != %s)", 251 this.numHashFunctions, 252 that.numHashFunctions); 253 checkArgument( 254 this.bitSize() == that.bitSize(), 255 "BloomFilters must have the same size underlying bit arrays (%s != %s)", 256 this.bitSize(), 257 that.bitSize()); 258 checkArgument( 259 this.strategy.equals(that.strategy), 260 "BloomFilters must have equal strategies (%s != %s)", 261 this.strategy, 262 that.strategy); 263 checkArgument( 264 this.funnel.equals(that.funnel), 265 "BloomFilters must have equal funnels (%s != %s)", 266 this.funnel, 267 that.funnel); 268 this.bits.putAll(that.bits); 269 } 270 271 @Override 272 public boolean equals(@Nullable Object object) { 273 if (object == this) { 274 return true; 275 } 276 if (object instanceof BloomFilter) { 277 BloomFilter<?> that = (BloomFilter<?>) object; 278 return this.numHashFunctions == that.numHashFunctions 279 && this.funnel.equals(that.funnel) 280 && this.bits.equals(that.bits) 281 && this.strategy.equals(that.strategy); 282 } 283 return false; 284 } 285 286 @Override 287 public int hashCode() { 288 return Objects.hashCode(numHashFunctions, funnel, strategy, bits); 289 } 290 291 /** 292 * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link 293 * BloomFilter} with false positive probability 3%. 294 * 295 * <p>Note that if the {@code Collector} receives significantly more elements than specified, the 296 * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive 297 * probability. 298 * 299 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 300 * is. 301 * 302 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 303 * ensuring proper serialization and deserialization, which is important since {@link #equals} 304 * also relies on object identity of funnels. 305 * 306 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 307 * @param expectedInsertions the number of expected insertions to the constructed {@code 308 * BloomFilter}; must be positive 309 * @return a {@code Collector} generating a {@code BloomFilter} of the received elements 310 * @since 23.0 311 */ 312 public static <T> Collector<T, ?, BloomFilter<T>> toBloomFilter( 313 Funnel<? super T> funnel, long expectedInsertions) { 314 return toBloomFilter(funnel, expectedInsertions, 0.03); 315 } 316 317 /** 318 * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link 319 * BloomFilter} with the specified expected false positive probability. 320 * 321 * <p>Note that if the {@code Collector} receives significantly more elements than specified, the 322 * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive 323 * probability. 324 * 325 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 326 * is. 327 * 328 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 329 * ensuring proper serialization and deserialization, which is important since {@link #equals} 330 * also relies on object identity of funnels. 331 * 332 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 333 * @param expectedInsertions the number of expected insertions to the constructed {@code 334 * BloomFilter}; must be positive 335 * @param fpp the desired false positive probability (must be positive and less than 1.0) 336 * @return a {@code Collector} generating a {@code BloomFilter} of the received elements 337 * @since 23.0 338 */ 339 public static <T> Collector<T, ?, BloomFilter<T>> toBloomFilter( 340 Funnel<? super T> funnel, long expectedInsertions, double fpp) { 341 checkNotNull(funnel); 342 checkArgument( 343 expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); 344 checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); 345 checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); 346 return Collector.of( 347 () -> BloomFilter.create(funnel, expectedInsertions, fpp), 348 BloomFilter::put, 349 (bf1, bf2) -> { 350 bf1.putAll(bf2); 351 return bf1; 352 }, 353 Collector.Characteristics.UNORDERED, 354 Collector.Characteristics.CONCURRENT); 355 } 356 357 /** 358 * Creates a {@link BloomFilter} with the expected number of insertions and expected false 359 * positive probability. 360 * 361 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 362 * will result in its saturation, and a sharp deterioration of its false positive probability. 363 * 364 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 365 * is. 366 * 367 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 368 * ensuring proper serialization and deserialization, which is important since {@link #equals} 369 * also relies on object identity of funnels. 370 * 371 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 372 * @param expectedInsertions the number of expected insertions to the constructed {@code 373 * BloomFilter}; must be positive 374 * @param fpp the desired false positive probability (must be positive and less than 1.0) 375 * @return a {@code BloomFilter} 376 */ 377 public static <T> BloomFilter<T> create( 378 Funnel<? super T> funnel, int expectedInsertions, double fpp) { 379 return create(funnel, (long) expectedInsertions, fpp); 380 } 381 382 /** 383 * Creates a {@link BloomFilter} with the expected number of insertions and expected false 384 * positive probability. 385 * 386 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 387 * will result in its saturation, and a sharp deterioration of its false positive probability. 388 * 389 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 390 * is. 391 * 392 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 393 * ensuring proper serialization and deserialization, which is important since {@link #equals} 394 * also relies on object identity of funnels. 395 * 396 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 397 * @param expectedInsertions the number of expected insertions to the constructed {@code 398 * BloomFilter}; must be positive 399 * @param fpp the desired false positive probability (must be positive and less than 1.0) 400 * @return a {@code BloomFilter} 401 * @since 19.0 402 */ 403 public static <T> BloomFilter<T> create( 404 Funnel<? super T> funnel, long expectedInsertions, double fpp) { 405 return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64); 406 } 407 408 @VisibleForTesting 409 static <T> BloomFilter<T> create( 410 Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) { 411 checkNotNull(funnel); 412 checkArgument( 413 expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); 414 checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); 415 checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); 416 checkNotNull(strategy); 417 418 if (expectedInsertions == 0) { 419 expectedInsertions = 1; 420 } 421 /* 422 * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size 423 * is proportional to -log(p), but there is not much of a point after all, e.g. 424 * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares! 425 */ 426 long numBits = optimalNumOfBits(expectedInsertions, fpp); 427 int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); 428 try { 429 return new BloomFilter<T>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy); 430 } catch (IllegalArgumentException e) { 431 throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); 432 } 433 } 434 435 /** 436 * Creates a {@link BloomFilter} with the expected number of insertions and a default expected 437 * false positive probability of 3%. 438 * 439 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 440 * will result in its saturation, and a sharp deterioration of its false positive probability. 441 * 442 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 443 * is. 444 * 445 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 446 * ensuring proper serialization and deserialization, which is important since {@link #equals} 447 * also relies on object identity of funnels. 448 * 449 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 450 * @param expectedInsertions the number of expected insertions to the constructed {@code 451 * BloomFilter}; must be positive 452 * @return a {@code BloomFilter} 453 */ 454 public static <T> BloomFilter<T> create(Funnel<? super T> funnel, int expectedInsertions) { 455 return create(funnel, (long) expectedInsertions); 456 } 457 458 /** 459 * Creates a {@link BloomFilter} with the expected number of insertions and a default expected 460 * false positive probability of 3%. 461 * 462 * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, 463 * will result in its saturation, and a sharp deterioration of its false positive probability. 464 * 465 * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} 466 * is. 467 * 468 * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of 469 * ensuring proper serialization and deserialization, which is important since {@link #equals} 470 * also relies on object identity of funnels. 471 * 472 * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use 473 * @param expectedInsertions the number of expected insertions to the constructed {@code 474 * BloomFilter}; must be positive 475 * @return a {@code BloomFilter} 476 * @since 19.0 477 */ 478 public static <T> BloomFilter<T> create(Funnel<? super T> funnel, long expectedInsertions) { 479 return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions 480 } 481 482 // Cheat sheet: 483 // 484 // m: total bits 485 // n: expected insertions 486 // b: m/n, bits per insertion 487 // p: expected false positive probability 488 // 489 // 1) Optimal k = b * ln2 490 // 2) p = (1 - e ^ (-kn/m))^k 491 // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b 492 // 4) For optimal k: m = -nlnp / ((ln2) ^ 2) 493 494 /** 495 * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the 496 * expected insertions and total number of bits in the Bloom filter. 497 * 498 * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. 499 * 500 * @param n expected insertions (must be positive) 501 * @param m total number of bits in Bloom filter (must be positive) 502 */ 503 @VisibleForTesting 504 static int optimalNumOfHashFunctions(long n, long m) { 505 // (m / n) * log(2), but avoid truncation due to division! 506 return Math.max(1, (int) Math.round((double) m / n * Math.log(2))); 507 } 508 509 /** 510 * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified 511 * expected insertions, the required false positive probability. 512 * 513 * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the 514 * formula. 515 * 516 * @param n expected insertions (must be positive) 517 * @param p false positive rate (must be 0 < p < 1) 518 */ 519 @VisibleForTesting 520 static long optimalNumOfBits(long n, double p) { 521 if (p == 0) { 522 p = Double.MIN_VALUE; 523 } 524 return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); 525 } 526 527 private Object writeReplace() { 528 return new SerialForm<T>(this); 529 } 530 531 private static class SerialForm<T> implements Serializable { 532 final long[] data; 533 final int numHashFunctions; 534 final Funnel<? super T> funnel; 535 final Strategy strategy; 536 537 SerialForm(BloomFilter<T> bf) { 538 this.data = LockFreeBitArray.toPlainArray(bf.bits.data); 539 this.numHashFunctions = bf.numHashFunctions; 540 this.funnel = bf.funnel; 541 this.strategy = bf.strategy; 542 } 543 544 Object readResolve() { 545 return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy); 546 } 547 548 private static final long serialVersionUID = 1; 549 } 550 551 /** 552 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java 553 * serialization). This has been measured to save at least 400 bytes compared to regular 554 * serialization. 555 * 556 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter. 557 */ 558 public void writeTo(OutputStream out) throws IOException { 559 // Serial form: 560 // 1 signed byte for the strategy 561 // 1 unsigned byte for the number of hash functions 562 // 1 big endian int, the number of longs in our bitset 563 // N big endian longs of our bitset 564 DataOutputStream dout = new DataOutputStream(out); 565 dout.writeByte(SignedBytes.checkedCast(strategy.ordinal())); 566 dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor 567 dout.writeInt(bits.data.length()); 568 for (int i = 0; i < bits.data.length(); i++) { 569 dout.writeLong(bits.data.get(i)); 570 } 571 } 572 573 /** 574 * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code 575 * BloomFilter}. 576 * 577 * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here. 578 * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate 579 * the original Bloom filter! 580 * 581 * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not 582 * appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method. 583 */ 584 public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<? super T> funnel) 585 throws IOException { 586 checkNotNull(in, "InputStream"); 587 checkNotNull(funnel, "Funnel"); 588 int strategyOrdinal = -1; 589 int numHashFunctions = -1; 590 int dataLength = -1; 591 try { 592 DataInputStream din = new DataInputStream(in); 593 // currently this assumes there is no negative ordinal; will have to be updated if we 594 // add non-stateless strategies (for which we've reserved negative ordinals; see 595 // Strategy.ordinal()). 596 strategyOrdinal = din.readByte(); 597 numHashFunctions = UnsignedBytes.toInt(din.readByte()); 598 dataLength = din.readInt(); 599 600 Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal]; 601 long[] data = new long[dataLength]; 602 for (int i = 0; i < data.length; i++) { 603 data[i] = din.readLong(); 604 } 605 return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy); 606 } catch (RuntimeException e) { 607 String message = 608 "Unable to deserialize BloomFilter from InputStream." 609 + " strategyOrdinal: " 610 + strategyOrdinal 611 + " numHashFunctions: " 612 + numHashFunctions 613 + " dataLength: " 614 + dataLength; 615 throw new IOException(message, e); 616 } 617 } 618}