Java 基于CAS手动实现简单连接池

该代码示例展示了一个简单的线程池实现,使用了AtomicIntegerArray来管理连接状态,当获取或释放连接时,会进行状态的原子性更新。线程池未处理动态扩容和收缩,没有超时等待机制,且在等待连接时可能会发生不可恢复的中断异常。
摘要由CSDN通过智能技术生成

并未考虑动态扩容与收缩,可用性检测,超时等待

public class Test {

    @SneakyThrows
    public static void main(String[] args) {
        // new Thread(() -> {}, "").start();
        // log.debug("");
        Pool pool = new Pool(2);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                Connection connection = pool.getConnection();
                try {
                    Thread.sleep(new Random().nextInt(2));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                pool.free(connection);
            }, String.valueOf(i)).start();

        }
    }
}

@Slf4j(topic = "c.Pool")
class Pool {
    private static int poolSize;
    private static Connection[] connections;
    private static AtomicIntegerArray states;  // 0未连接 1 已连接

    public Pool(int poolSize) {
        this.poolSize = poolSize;
        connections = new Connection[poolSize];
        for (int i = 0; i < poolSize; i++) {
            connections[i] = new MockConnection("Connection -> " + i);  //模拟已经连接
        }
        states = new AtomicIntegerArray(poolSize);
    }

    public Connection getConnection() {
        while (true) {
            for (int i = 0; i < poolSize; i ++) {
                if (states.get(i) == 0) {
                    if (states.compareAndSet(i, 0, 1)) {
                        log.debug("getConnection -> {}", i);
                        return connections[i];
                    }
                }
            }
            synchronized (this) {
                try {
                    log.debug("wait");
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void free(Connection connection) {
        for (int i = 0; i < poolSize; i ++) {
            if (connection == connections[i]) {
                states.set(i, 0);
                log.debug("free -> {}", i);
                synchronized (this) {
                    this.notifyAll();
                    log.debug("notifyAll {}", i);
                }
                break;
            }
        }
    }
}

class MockConnection implements Connection{

    private String name;

    public MockConnection (String name) {
        this.name = name;
    }
	//...implements methods
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值