您的位置:首页 > 产品设计 > UI/UE

java集合类深入分析之Queue篇(3)

2017-03-14 00:00 316 查看
摘要: 并发-换一种方式

针对篇(2),做了一些改进:

public class XenPool {
private static Logger logger = Logger.getLogger(XenPool.class);
private AtomicInteger xenConnectionCount=new AtomicInteger(0);

private static Map<String,AtomicInteger> countPool = new ConcurrentHashMap(100);
public XenPool(){}

public static Connection getConnect(XenServer xenServer) {
URL url =null;
try {
url = new URL(xenServer.Hostname);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
String host=url.getHost();
Connection connection = null;
try {
connection = new Connection(new URL(xenServer.Hostname), XenServer.REPLY_WAIT, XenServer.CONNECT_WAIT);
} catch (MalformedURLException e) {
logger.error("xenserver[" + xenServer.Hostname + "]建立连接异常!",e);
}
try {
Session.loginWithPassword(connection, xenServer.Username, SystemService.decryptPassword(xenServer.Password), APIVersion.latest().toString());
increase(host);
logger.debug("TID["+Thread.currentThread().getId()+"],xenserver[" + host + "]连接建立,连接数["+getConnectionCount(host)+"]!");
} catch (Types.XenAPIException e) {
logger.error("xenserver[" + xenServer.Hostname + "]XenAPIException异常!",e);
} catch (XmlRpcException e) {
logger.error("xenserver[" + xenServer.Hostname + "]XmlRpcException异常!",e);
} catch (Exception ex){
logger.error(ex.getMessage(),ex);
}
return connection;
}

public static void disconnect (Connection connection) {
String host= null;
try {
host = connection.getConfig().getServerURL().getHost();
} catch (Exception e) {
e.printStackTrace();
}
if (connection!=null){//当连接不用时放到队列里
try {
Session.logout(connection);
decrement(host);
logger.debug("TID["+Thread.currentThread().getId()+"],xenserver[" + host + "]连接释放,连接数["+getConnectionCount(host)+"]!");
} catch (Types.XenAPIException e) {
logger.error("xenserver[" + host + "]释放异常!",e);
} catch (XmlRpcException e) {
logger.error("xenserver[" + host + "]释放异常!",e);
}
}
}

/**
* wzw add 上次被清除了
* @param xenServer
*/
public static void removeHost (XenServer xenServer){
if (xenServer!=null && StringUtils.isNotBlank(xenServer.Hostname)) {
URL url =null;
try {
url = new URL(xenServer.Hostname);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String host=url.getHost();
countPool.remove(host);
}
}

private static void increase(String host){
AtomicInteger count = countPool.get(host);
if (count == null) {
count = new AtomicInteger(0);
countPool.put(host, count);
}
count.incrementAndGet();
}
private static void decrement(String host){
AtomicInteger count = countPool.get(host);
if (count == null) {
return ;
}
count.decrementAndGet();
}

private static int getConnectionCount(String host){
AtomicInteger count = countPool.get(host);
if (count == null) {
return 0;
}
return count.get();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: