简体   繁体   English

Java BitSet线程对于并发只读操作是否安全?

[英]Is Java BitSet thread safe for concurrent readonly operations

I have multiple threads in my application accessing a BitSet concurrently. 我的应用程序中有多个线程可以同时访问BitSet。 The documentation says: 文件说:

A BitSet is not safe for multithreaded use without external synchronization. 如果没有外部同步,则BitSet对于多线程使用是不安全的。

It doesn't say if it is not safe for reading or writing. 它没有说读或写是否不安全。 Can anybody explain. 谁能解释。

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. 一个BitSet仅用于只读操作安全的,如果有是初始化的最后一个动作之间的关系“之前发生” BitSet和阅读的行动。

The simplest way to achieve this is using a final . 实现此目的的最简单方法是使用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". 这足以确保BitSet被“安全发布”。

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. 但是,如果您不执行此类操作,则无法保证读取BitSet线程将看到完全初始化的状态。

Another alternative to explicit synchronization is to use a volatile variable to hold the reference to the BitSet . 显式同步的另一种替代方法是使用一个volatile变量来保存对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; 注意,相同的推理适用于所有非线程安全的“有效不变”的对象。 ie objects that have mutable state which you don't mutate. 即具有可变状态的对象,并且您不会对其进行突变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM