自定义对象池接口

本文介绍了一种自定义对象池的设计与实现方法,包括CustomPooledObject接口、CustomPooledObjectFactory工厂和CustomObjectPool连接池的实现。通过对象池化技术,可以有效减少频繁创建和销毁对象的时间开销,特别适用于数据库连接、TCP和HTTP连接等耗时对象的管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义对象池接口

github 地址

为什么要用对象池

对象池就是把一群已经实例化过的对象,在使用完了以后保存起来,这样下次需要用到的时候,就不用重新创建。你可能会疑惑,这样存起来岂不是占用内存空间。对的,但是优势在于,如果是一些建立时比较耗时的对象,那么就可以做到用空间换时间了,例如数据库连接对象、一些TCP、HTTP连接对象等,这些对象在创建和销毁是比较耗时的。

自定义实现

这里主要涉及到以下接口:

  • CustomPooledObject:被池化的对象
  • CustomPooledObjectFactory:创建池化对象的工厂
  • CustomObjectPool:对象池

CustomPooledObject

贴下代码:

public interface CustomPooledObject extends Validate {
    void destroy();
}

这个接口的功能比较简单,使用的时候,实现此接口,即可将对象池化。
贴一段使用代码:

public class TestPooledObject implements CustomPooledObject {
    private int age;
    private String name;

    public TestPooledObject() {
    }

    public TestPooledObject(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void destroy() {
    }

    @Override
    public boolean validate() {
        return ObjectUtil.isNotNull(this);
    }

    @Override
    public String toString() {
        return "TestPooledObject{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

这里要实现destroyvalidate方法,前者是销毁当前对象,后者是验证当前对象是否可用。

CustomPooledObjectFactory

这个接口就更简单了,只有一个创建对象的方法:

public interface CustomPooledObjectFactory<CustomPooledObject> {
    CustomPooledObject create();
}

使用时就这么做:

@Component
public class TestObjectFactory implements CustomPooledObjectFactory<CustomPooledObject> {
    private int i;
    @Override
    public CustomPooledObject create() {
        TestPooledObject testPooledObject = new TestPooledObject(++i,""+i);
        return testPooledObject;
    }
}

只需要在create方法里面,把需要池化的对象创建出来即可。

CustomObjectPool

连接池的实现类,里面操作的都是接口,不需要额外开发,直接上代码吧:

public class CustomObjectPool implements ObjectPool<CustomPooledObject> {

    private final static int DEFAULE_CORE_POOL_SIZE = 1;
    private final static int DEFAULE_MAX_POOL_SIZE = 5;
    private final static int DEFAULT_OFFER_TIME = 3;
    private final static int DEFAULT_POLL_TIME = 3;
    private CustomPooledObjectFactory<CustomPooledObject> customPooledObjectFactory;
    private int maxPoolSize;
    private int corePoolSize;
    private int offerTime;
    private int pollTime;
    private AtomicInteger activeNum = new AtomicInteger();
    private BlockingQueue<CustomPooledObject> pool;

    public CustomObjectPool(CustomPooledObjectFactory<CustomPooledObject> customPooledObjectFactory) {
        this(DEFAULE_CORE_POOL_SIZE, DEFAULE_MAX_POOL_SIZE, DEFAULT_POLL_TIME, DEFAULT_OFFER_TIME, customPooledObjectFactory);
    }

    public CustomObjectPool(int corePoolSize, int maxPoolSize, int pollTime, int offerTime, CustomPooledObjectFactory<CustomPooledObject> customPooledObjectFactory) {
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        this.pollTime = pollTime;
        this.offerTime = offerTime;
        this.customPooledObjectFactory = customPooledObjectFactory;
        pool = new ArrayBlockingQueue<>(maxPoolSize);
        init();
    }

    public void init() {
        for (int i = 0; i < corePoolSize; i++) {
            try {
                addObject();
            } catch (Exception e) {
                throw new RuntimeException("对象池初始化失败!");
            }
        }
    }

    /**
     * 从池中取出一个对象
     */
    @Override
    public CustomPooledObject borrowObject() throws Exception, NoSuchElementException, IllegalStateException {
        if (getNumIdle() == 0 && getNumActive() < maxPoolSize) {
            synchronized (this) {
                if (getNumIdle() == 0 && getNumActive() < maxPoolSize) {
                    return directReturnObject();
                }
            }
        }
        CustomPooledObject customPooledObject = pool.poll(pollTime, TimeUnit.SECONDS);
        if (ObjectUtil.validate(customPooledObject)) {
            activeNum.incrementAndGet();
            return customPooledObject;
        } else {
            return directReturnObject();
        }
    }

    /**
     * 归还一个对象到池中
     */
    @Override
    public void returnObject(CustomPooledObject customPooledObject) throws Exception {
        try {
            if (ObjectUtil.validate(customPooledObject) && !pool.offer(customPooledObject, offerTime, TimeUnit.SECONDS)) {
                destroyObject(customPooledObject);
            }
        } finally {
            activeNum.decrementAndGet();
        }
    }

    /**
     * 是指定对象从池中失效
     */
    @Override
    public void invalidateObject(CustomPooledObject customPooledObject) throws Exception {
        pool.remove(customPooledObject);
    }

    /**
     * 池中增加一个对象
     */
    @Override
    public void addObject() throws Exception, IllegalStateException, UnsupportedOperationException {
        pool.offer(createObject(), offerTime, TimeUnit.SECONDS);
    }

    /**
     * 获取池中空闲对象数量
     */
    @Override
    public int getNumIdle() {
        return pool.size();
    }

    /**
     * 获取使用中的对象数量
     */
    @Override
    public int getNumActive() {
        return activeNum.get();
    }

    /**
     * 销毁指定对象
     */
    private void destroyObject(CustomPooledObject customPooledObject) {
        if (ObjectUtil.validate(customPooledObject)) {
            customPooledObject.destroy();
        }
    }

    /**
     * 创建对象并返回
     */
    private CustomPooledObject createObject() {
        return customPooledObjectFactory.create();
    }

    /**
     * 创建的对象直接返回
     */
    private synchronized CustomPooledObject directReturnObject() {
        activeNum.incrementAndGet();
        return createObject();
    }

    /**
     * 清空对象池
     */
    @Override
    public void clear() throws Exception, UnsupportedOperationException {
        pool.clear();
    }

    /**
     * 关闭对象池
     */
    @Override
    public void close() {
        pool.clear();
        pool = null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值