Is Java BitSet thread safe for concurrent readonly operations

我只是一个虾纸丫 提交于 2019-12-20 03:18:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33474905/is-java-bitset-thread-safe-for-concurrent-readonly-operations

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