Search code examples
javamultithreadingconcurrencythread-safetybitset

Is Java BitSet thread safe for concurrent readonly operations


I have multiple threads in my application accessing a BitSet concurrently. The documentation says:

A BitSet is not safe for multithreaded use without external synchronization.

It doesn't say if it is not safe for reading or writing. Can anybody explain.


Solution

  • A BitSet is only safe for read-only operations if there is a "happens before" relationship between the last action that initializes the BitSet and the actions that read it.

    The simplest way to achieve this is using a final. For example:

    public class BitsetHolder {
        private final BitSet b;
    
        public BitSetHolder() {
            b = new BitSet();
            // operations to initialize b.
        }
    
        public BitSet getBitSet() {
            return b;
        }
    }
    

    This is sufficient to ensure that the BitSet is "safely published".

    However, if you don't do something like this, there is no guarantee that threads that read the BitSet will see the fully initialized state.

    Another alternative to explicit synchronization is to use a volatile variable to hold the reference to the BitSet. However, that inserts a memory barrier on each read and write of the variable.


    Note that the same reasoning applies to all non-thread-safe "effectively immutable" objects; i.e. objects that have mutable state which you don't mutate.