In this example, we present two types of implementations of bloom filter which have similarities and differences.

The similarity is that both support capacity extension, we can extend the capacity by creating another layer of bloom filter to hold the new coming data. Once this layer is full, deliver the new data to next layer which is a recursive process;

Th difference is that only one support deletion operation. The naive one that only supports add but with good efficiency and conserves a great amount of memory. The other supports both add and remove, the cost is a great deal of extra memory space. It depends on different situations and applications when choosing a proper one.

import java.io.Serializable;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Random;


public class BloomFilter {

    // In this example, we present two types of implementations of bloom filter which have similarities and differences.

    // The similarity is that both support capacity extension, we can extend the capacity by creating another layer of
    // bloom filter to hold the new coming data. Once this layer is full, deliver the new data to next layer which is a
    // recursive process;

    // Th difference is that only one support deletion operation. The naive one that only supports add but with good
    // efficiency and conserves a great amount of memory. The other supports both add and remove, the cost is a great
    // deal of extra memory space. It depends on different situations and applications when choosing a proper one.

    public static void main(String[] args) {

        FlexibleBloomFilter fbf = new FlexibleBloomFilter<Integer>(10, 10000, 2);
        for (int i = 0; i < 55000; i++) {
            fbf.add(i);

            if (Math.random() > 0.9) {
                int val = new Random().nextInt(20000);
                System.out.println("Current i=" + i + ", contains " + val + ": " + fbf.contains(val));
            }
        }

        System.out.println(fbf.getFalsePositiveProbability());

        CountableBloomFilter cbf = new CountableBloomFilter(10, 1000, 2);

        int count = 0;
        while (true) {
            for (int i = 0; i < 3000; i++) {
                cbf.add(i);
            }

            count++;
            if (count > 5) {
                break;
            }
        }

        for (int i = 0; i < count + 2; i++) {
            cbf.remove(10);
            System.out.println("Current i=" + i + ", contains " + 10 + ": " + cbf.contains(10));
        }
    }
}

class FlexibleBloomFilter<E> implements Serializable {

    // This is a flexible BloomFilter that support multi-layer keep data. Once the added element exceeds
    // the capacity of the filter, the accuracy will drop dramatically. It is necessary to instantiate another
    // filter to keep the extra data so that the filter can maintain good condition.

    // By the way, this version does not support element deletion.

    // MD5 assure good enough accuracy in most circumstances.
    static String hashName = "MD5";
    static MessageDigest digestFunction = null;

    static {
        try {
            digestFunction = java.security.MessageDigest.getInstance(hashName);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    FlexibleBloomFilter<E> next = null;
    // translate string data to char array with below charset
    Charset charset = Charset.forName("UTF-8");
    private BitSet bitset = null;
    private int bitSetSize = 0;
    private double bitsPerElement = 8;

    // expected (maximum) number of elements to be added
    private int expectedElementNum;

    // number of elements actually added to the Bloom filter
    private int addedElementNum = 0;

    // number of hash functions
    private int hashFuncNum = 8;

    public FlexibleBloomFilter(double bitsPerElement, int expectedElementNum, int hashFuncNum) {
        this.expectedElementNum = expectedElementNum;
        this.hashFuncNum = hashFuncNum;
        this.bitsPerElement = bitsPerElement;
        this.bitSetSize = (int) Math.ceil(bitsPerElement * expectedElementNum);
        this.bitset = new BitSet(bitSetSize);
    }

    // (1 - e^(-hashFuncNum * n / m)) ^ hashFuncNum
    public List<Double> getFalsePositiveProbability() {
        double fpp = Math.pow((1 - Math.exp(-hashFuncNum * addedElementNum / (double) bitSetSize)), hashFuncNum);

        // the last filter creates a array list used to keep false positive probability for each layer's filter.
        if (next == null) {
            List<Double> fpps = new ArrayList<>();
            fpps.add(fpp);

            return fpps;
        }

        List<Double> fpps = next.getFalsePositiveProbability();
        fpps.add(0, fpp);

        return fpps;
    }

    public void add(E element) {

        // the next layer filter will exists if current layer is full
        if (next != null) {
            next.add(element);

            return;
        }

        int[] hashes = createHashes(element.toString(), hashFuncNum);

        for (int hash : hashes) {
            bitset.set(Math.abs(hash % bitSetSize), true);
        }

        addedElementNum++;

        // duplicate another layer of filter if current is full
        if (addedElementNum > expectedElementNum) {
            next = new FlexibleBloomFilter<>(bitsPerElement, expectedElementNum, hashFuncNum);
        }
    }

    public boolean contains(E element) {
        int[] hashes = createHashes(element.toString(), hashFuncNum);

        for (int hash : hashes) {
            if (!bitset.get(Math.abs(hash % bitSetSize))) {
                if (next == null) {
                    return false;
                }

                // check the next layer if not found at current layer.
                return next.contains(element);
            }
        }

        return true;
    }

    public synchronized int[] createHashes(String str, int hashes) {

        // set the function synchronized in case of multi thread circumstances.

        byte[] data = str.getBytes(charset);

        int[] result = new int[hashes];

        int k = 0;
        byte salt = 0;

        while (k < hashes) {
            byte[] digest;

            digestFunction.update(salt);

            salt++;

            digest = digestFunction.digest(data);

            for (int i = 0; i < digest.length / 4 && k < hashes; i++) {
                int h = 0;

                for (int j = (i * 4); j < (i * 4) + 4; j++) {
                    h <<= 8;
                    h |= ((int) digest[j]) & 0xFF;
                }

                result[k] = h;
                k++;
            }
        }

        return result;
    }
}

class CountableBloomFilter<E> implements Serializable {

    // This is a flexible BloomFilter that support multi-layer keep data. Once the added element exceeds
    // the capacity of the filter, the accuracy will drop dramatically. It is necessary to instantiate another
    // filter to keep the extra data so that the filter can maintain good condition.

    // This version support element deletion, but the count limit for same element is 2^16, so if there are more
    // than 2^16 duplicated elements, error occurs. But you can increase the capacity by change the bitset type,
    // currently the type is char, but for more large scale application, int or long will be more favorable.

    // MD5 assure good enough accuracy in most circumstances.
    static String hashName = "MD5";
    static MessageDigest digestFunction = null;

    static {
        try {
            digestFunction = java.security.MessageDigest.getInstance(hashName);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    CountableBloomFilter<E> next = null;
    // translate string data to char array with below charset
    Charset charset = Charset.forName("UTF-8");
    private char[] bitset = null;
    private int bitSetSize = 0;
    private double bitsPerElement = 8;

    // expected (maximum) number of elements to be added
    private int expectedElementNum;

    // number of elements actually added to the Bloom filter
    private int addedElementNum = 0;

    // number of hash functions
    private int hashFuncNum = 8;

    public CountableBloomFilter(double bitsPerElement, int expectedElementNum, int hashFuncNum) {
        this.expectedElementNum = expectedElementNum;
        this.hashFuncNum = hashFuncNum;
        this.bitsPerElement = bitsPerElement;
        this.bitSetSize = (int) Math.ceil(bitsPerElement * expectedElementNum);
        this.bitset = new char[bitSetSize];
    }

    // (1 - e^(-hashFuncNum * n / m)) ^ hashFuncNum
    public List<Double> getFalsePositiveProbability() {
        double fpp = Math.pow((1 - Math.exp(-hashFuncNum * addedElementNum / (double) bitSetSize)), hashFuncNum);

        // the last filter creates a array list used to keep false positive probability for each layer's filter.
        if (next == null) {
            List<Double> fpps = new ArrayList<>();
            fpps.add(fpp);

            return fpps;
        }

        List<Double> fpps = next.getFalsePositiveProbability();
        fpps.add(0, fpp);

        return fpps;
    }

    public void add(E element) {
        // the next layer filter will exists if current layer is full
        if (next != null) {
            next.add(element);

            return;
        }

        int[] hashes = createHashes(element.toString(), hashFuncNum);

        for (int hash : hashes) {
            bitset[Math.abs(hash % bitSetSize)]++;
        }

        addedElementNum++;

        // duplicate another layer of filter if current is full
        if (addedElementNum > expectedElementNum) {
            next = new CountableBloomFilter<>(bitsPerElement, expectedElementNum, hashFuncNum);
        }
    }

    public void remove(E element) {

        // the duplicate element may exists in several layers, you cannot walk through every layer
        // and delete all of them. Instead, if you find them in certain layer, delete it then return,
        // rather than dig down.

        if (currentLayerContains(element)) {
            int[] hashes = createHashes(element.toString(), hashFuncNum);

            for (int hash : hashes) {
                bitset[Math.abs(hash % bitSetSize)]--;
            }

            addedElementNum--;
        }
        // check out if the given element lies in the next layer
        else if (next != null) {
            next.remove(element);
        }
    }

    private boolean currentLayerContains(E element) {
        int[] hashes = createHashes(element.toString(), hashFuncNum);

        for (int hash : hashes) {
            if (bitset[Math.abs(hash % bitSetSize)] <= 0) {
                return false;
            }
        }

        return true;
    }

    public boolean contains(E element) {
        int[] hashes = createHashes(element.toString(), hashFuncNum);

        for (int hash : hashes) {
            if (bitset[Math.abs(hash % bitSetSize)] <= 0) {
                if (next == null) {
                    return false;
                }

                // check the next layer if not found at current layer.
                return next.contains(element);
            }
        }

        return true;
    }

    public synchronized int[] createHashes(String str, int hashes) {

        // set the function synchronized in case of multi thread circumstances.

        byte[] data = str.getBytes(charset);

        int[] result = new int[hashes];

        int k = 0;
        byte salt = 0;

        while (k < hashes) {
            byte[] digest;

            digestFunction.update(salt);

            salt++;

            digest = digestFunction.digest(data);

            for (int i = 0; i < digest.length / 4 && k < hashes; i++) {
                int h = 0;

                for (int j = (i * 4); j < (i * 4) + 4; j++) {
                    h <<= 8;
                    h |= ((int) digest[j]) & 0xFF;
                }

                result[k] = h;
                k++;
            }
        }

        return result;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-12 09:55:07

results matching ""

    No results matching ""