?? socketchannelpool.java
字號:
package org.pool;import java.io.IOException;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketException;import java.net.UnknownHostException;import java.nio.channels.SocketChannel;public class SocketChannelPool implements ISocketChannelPool { private InetSocketAddress inetSockketaddress; private static Object object_lock = new Object(); private static SocketChannelPool channelpool = null; /** * 默認的最大連接數(shù) */ private int max_size = 20; /** * 默認的最小連接數(shù) */ private int min_size = 10; /** * _SocketChannel 池數(shù)組 */ private _SocketChannel[] socketChannelPool = null; private SocketChannelPool(String host, int port, int minSize, int maxSize) throws Exception { this.min_size = minSize; this.max_size = maxSize; inetSockketaddress = new InetSocketAddress(host, port); init(); } @Override public void destroy() { for (int i = 0; i < socketChannelPool.length; i++) { if (socketChannelPool[i] != null) { _SocketChannel adapter = (_SocketChannel) socketChannelPool[i]; adapter.destroy(); System.out.print(" . "); } } System.out.println("\ndestory success ...."); } @Override public _SocketChannel getConnection() throws SocketException { // TODO Auto-generated method stub _SocketChannel s = null; synchronized (socketChannelPool) { for (int i = 0; i < socketChannelPool.length; i++) { if (socketChannelPool[i] != null) { // 如果有空閑的連接,返回一個空閑連接,如果沒有,繼續(xù)循環(huán) if (socketChannelPool[i].isFree()) { s = socketChannelPool[i]; s.setBusy(); break; } else { System.out.println("等待程序釋放鏈接"); try { Thread.currentThread().sleep(100); return getConnection(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } continue; } } else { // 如果連接為空,證明超過最小連接數(shù),重新生成連接 try { s = socketChannelPool[i] = new _SocketChannel( inetSockketaddress); } catch (Exception e) { // never throw } } } } return s; } @Override public void init() throws UnknownHostException, IOException { // TODO Auto-generated method stub socketChannelPool = new _SocketChannel[max_size]; for (int i = 0; i < min_size; i++) { socketChannelPool[i] = new _SocketChannel(inetSockketaddress); System.out.print(" . "); } System.out.println(); System.out.println("System init success ...."); } @Override public boolean isPooled() { // TODO Auto-generated method stub if (socketChannelPool != null) { return true; } else return false; } @Override public void restart() throws UnknownHostException, IOException { destroy(); init(); } public static SocketChannelPool newInstance(String host, int port, int minSize, int maxSize) throws Exception { if (channelpool == null) { synchronized (object_lock) { if (channelpool == null) { channelpool = new SocketChannelPool(host,port,minSize,maxSize); } } } return channelpool; }}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -