JAVA池化技术

本文介绍了对象池技术,主要用于管理和复用资源消耗大的对象,如线程池和数据库连接池。通过实现ImgClientTool接口,展示了如何创建一个连接池,包括初始化、获取和释放连接以及超时处理等功能,旨在优化资源使用效率。
摘要由CSDN通过智能技术生成

那些创建时间长,需要大量资源,创建后可重复使用的对象,这类对象往往是比较消耗资源的,为了节省资源开销,可以把对象缓存起来,需要的时候拿出来用,提高资源利用率
常见的有线程池、数据库连接池等

定义池的功能

public interface ImgClientTool {

    //初始化
    void init();

    //销毁
    void destroy();

    //获取连接
    ImgClient getConnection();

    //释放连接
    void release(ImgClient conn);

}

具体实现

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ImgClientImpl implements ImgClientTool {

    //最大连接数
    private int maxSize = 10;
    //存活数
    private AtomicInteger activeSize = new AtomicInteger(0);
    //闲置连接
    private LinkedBlockingQueue<ImgClient> idle;
    //繁忙连接
    private LinkedBlockingQueue<ImgClient> busy;

    //spring加载时初始化方法
    @PostConstruct
    public void init() {
        idle = new LinkedBlockingQueue();
        busy = new LinkedBlockingQueue();
    }

    public void destroy() {
        //不销毁
    }

    public ImgClient getConnection() {
        ImgClient conn = null;
        //从闲置池取出第一个连接并删除
        conn = idle.poll();
        if(null != conn){
            //放入繁忙连接池
            busy.offer(conn);
            return conn;
        }
        //存活连接数小于最大连接数,新建连接
        if(activeSize.get()<maxSize){
            if(activeSize.incrementAndGet()<=maxSize){
                conn = ImgClientFactory.createImgClient();
                //放入繁忙连接池
                busy.offer(conn);
                return conn;
            }
        }
        try {
            //在10秒内获取第一个连接,并删除
            conn = idle.poll(10, TimeUnit.SECONDS);
            if(null == conn){
                throw new RuntimeException("等待连接超时");
            }
            //放入繁忙连接池
            busy.offer(conn);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public void release(ImgClient conn) {
        //从繁忙池取出放入闲置池待用
        if(null != conn){
            busy.remove(conn);
            idle.offer(conn);
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值