java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java ConcurrentBitSet

Java中的ConcurrentBitSet使用小结

作者:有梦想的攻城狮

本文主要介绍了Java中的ConcurrentBitSet使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、核心澄清:Java标准库无内置ConcurrentBitSet

Java标准库(java.util包)中并未提供ConcurrentBitSet类。原生BitSet是线程不安全的,多线程环境下直接操作可能导致数据竞争和不一致。若需实现线程安全的位操作,需借助以下方案:

二、推荐方案:Eclipse Collections的ConcurrentBitSet

1. 第三方库介绍

Eclipse Collections(原GS Collections)是一个高性能的Java集合框架,提供了线程安全的ConcurrentBitSet实现,位于org.eclipse.collections.impl.bitset包中。其特点包括:

2. 使用示例

(1) 添加依赖

<dependency>
    <groupId>org.eclipse.collections</groupId>
    <artifactId>eclipse-collections</artifactId>
    <version>11.1.0</version>
</dependency>

(2) 基本操作

import org.eclipse.collections.impl.bitset.ConcurrentBitSet;

public class ConcurrentBitSetDemo {
    public static void main(String[] args) {
        // 创建并发BitSet实例
        ConcurrentBitSet bits = new ConcurrentBitSet(100);

        // 多线程操作示例
        ExecutorService executor = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 4; i++) {
            executor.execute(() -> {
                for (int j = 0; j < 1000; j++) {
                    // 线程安全地设置位
                    bits.set(j % 100);
                    // 线程安全地清除位
                    if (j % 50 == 0) {
                        bits.clear(j % 100);
                    }
                }
            });
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有任务完成
        }
        System.out.println("Final state: " + bits);
    }
}

(3) 高级功能

// 原子操作:检查并设置位(CAS)
boolean success = bits.compareAndSwap(index, expectedValue, newValue);

// 并发统计:计算true位的数量
int count = bits.cardinality();

// 并发位运算:与另一个BitSet执行AND操作
ConcurrentBitSet other = new ConcurrentBitSet(100);
bits.and(other);

三、替代方案:原生BitSet的线程安全封装

1. 同步包装法

通过synchronized关键字或Lock接口对BitSet的操作进行同步:

BitSet bits = new BitSet();
Lock lock = new ReentrantLock();

// 写操作
lock.lock();
try {
    bits.set(10);
} finally {
    lock.unlock();
}

// 读操作
lock.lock();
try {
    boolean value = bits.get(10);
} finally {
    lock.unlock();
}

2. 原子变量法

使用AtomicLongArray实现更细粒度的并发控制(适用于简单位操作):

AtomicLongArray array = new AtomicLongArray(100);

// 设置第50位
int index = 50 / 64;
int bit = 50 % 64;
long mask = 1L << bit;

boolean success = array.compareAndSwap(index, array.get(index), array.get(index) | mask);

四、方案对比与选型建议

方案优点缺点适用场景
Eclipse Collections ConcurrentBitSet线程安全、API丰富、性能优异需引入第三方库高并发位操作、复杂位运算
同步包装法实现简单、兼容原生BitSet性能瓶颈、粗粒度锁低并发场景、简单位操作
原子变量法细粒度控制、无锁化实现复杂、仅支持简单位操作高性能要求、简单位标记

五、总结

通过合理选择方案,可在多线程环境中高效、安全地处理位数据。

到此这篇关于Java中的ConcurrentBitSet使用小结的文章就介绍到这了,更多相关Java ConcurrentBitSet内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文