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