Is Java BitSet thread safe for concurrent readonly operations

淺唱寂寞╮ 提交于 2019-12-01 23:06:25

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!