📄 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; /** * 默认的最大连接数 */ private int max_size = 20; /** * 默认的最小连接数 */ private int min_size = 10; /** * _SocketChannel 池数组 */ 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) { // 如果有空闲的连接,返回一个空闲连接,如果没有,继续循环 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 { // 如果连接为空,证明超过最小连接数,重新生成连接 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 + -