Video in progress
What is BitSet, and when do you use it instead of Set<Integer> or boolean[]?
BitSet is a set of bits over a long[]: one bit for each non-negative integer. When the values are dense and bounded (ids, day numbers, ports), it takes hundreds of times less memory than a HashSet<Integer>, and set operations like and and or are very fast.
📖 Answer
The math: you need to store which of 10 million users logged in today, with ids in the range 0..10M.
HashSet<Integer>: aNode, anIntegerand a table slot for each element, about 50 bytes. For 10 million that is close to half a gigabyte.boolean[]: 1 byte per element, 10 MB.BitSet: 1 bit per element, about 1.25 MB.
BitSet today = new BitSet(10_000_000);
today.set(userId);
boolean active = today.get(userId);
BitSet both = (BitSet) today.clone();
both.and(yesterday); // those who logged in two days in a row
int count = both.cardinality(); // how many bits are set
for (int id = both.nextSetBit(0); id >= 0; id = both.nextSetBit(id + 1)) {
notify(id);
}
and, or and xor process 64 bits at a time, and cardinality counts with Long.bitCount, which turns into a single CPU instruction.
When it doesn't fit:
- the values are sparse and large: a single
set(2_000_000_000)allocates a 250 MB array. In that case you need a compressed bitmap library like RoaringBitmap; - negative numbers or
longvalues:BitSetworks only with a non-negativeintindex; - writing from several threads:
BitSetis not thread-safe and needs an external lock.
In an interview, BitSet is a good starting answer to "how would you store the online status of a million users in memory?". After that they ask about sparse ids and multiple instances, and that is where you move to a Redis bitmap or Roaring.
Sign up to mark studied questions and save your progress.