对象池

自己做的一个对象池。加了这个之后,性能确实好了很多,省下了重复创建对象的开销。

@Service
public class WebClientPool implements InitializingBean{
private Vector<WebClientWrapper> webClients=null;

@Value("${webClient.count}")
private String webClientCount;

/**
* Spring加载完后执行
*/
public void afterPropertiesSet() throws Exception {
int num = 0;
try {
num = Integer.parseInt(webClientCount);
} catch (Exception e) {
num = 50;
}
webClients = new Vector<WebClientWrapper>(num);
for(int i=0;i<num;i++){
webClients.add(new WebClientWrapper());
}
}

/**
* 获取对象池里可用的对象
*/
public synchronized WebClient getWebClient() throws InterruptedException{
for(WebClientWrapper webClientWrapper:webClients){
if(webClientWrapper.isUsed){
continue;
}
webClientWrapper.isUsed = true;
return webClientWrapper.webClient;
}
wait();
return getWebClient();
}

/**
* 释放对象,置为可用
*/
public synchronized void releaseWebClient(WebClient webClient){
for(WebClientWrapper webClientWrapper:webClients){
if(webClientWrapper.webClient.equals(webClient)){
webClientWrapper.isUsed=false;
webClientWrapper.webClient.close();
notifyAll();
return;
}
}
}

private static class WebClientWrapper{
WebClient webClient = WebClientFactory.getWebClient();
boolean isUsed = false;
}



}

你可能感兴趣的:(java,对象池)