日期:2014-05-20  浏览次数:20867 次

连接池得例子得小问题
[code=Java]import   java.net.Socket;
import   java.util.Hashtable;

public   class   ConnectionPool
{
private   static   final   int   CONNECTION_POOL_SIZE=10;
private   static   final   String   API_SERVER_HOST= "127.0.0.01 ";
private   static   final   int   API_SERVER_PORT=80;

private   static   ConnectionPool   self=null;

private   Hashtable   socketPool=null;//连接池
private   boolean[]   socketStatusArray=null;//连接得状态   true被占用false空闲

public   static   synchronized   void   init()
{
self=new   ConnectionPool();
self.socketPool=new   Hashtable();
self.socketStatusArray=new   boolean[CONNECTION_POOL_SIZE];

//初始化连接池
self.buildConnectionPool();
}
 
  public   static   synchronized   void   reset()
  {
  self=null;
  init();
}

public   static   Socket   getConnection()
{
if(self==null)
  init();
 
  int   i=0;
  for(i=0;i <CONNECTION_POOL_SIZE;i++)
  {
  if(!self.socketStatusArray[i])
  {
  self.socketStatusArray[i]=true;
  break;
  }
}
if(i <CONNECTION_POOL_SIZE)
  return   (Socket)self.socketPool.get(new   Integer(i));
else
{
System.out.println( "从连接池种获取与邮局得连接失败,已经没有空闲连接! ");

throw   new   RuntimeException( "No   enough   pooled   connection. ");
}
}

public   static   void   releaseConnection(Socket   Socket)
{
if(self==null)
init();

for(int   i=0;i <CONNECTION_POOL_SIZE;i++)
{
if(((Socket)self.socketPool.get(new   Integer(i)))==Socket)
{
self.socketStatusArray[i]=false;
break;
}
}
}

public   static   Socket   rebuildConnection(Socket   Socket)
{
if(self==null)
init();

Socket   newSocket=null;
for(int   i=0;i <CONNECTION_POOL_SIZE;i++)
{
try
{
if(((Socket)self.socketPool.get(new   Integer(i)))==Socket)
{
System.out.println( "重建连接池中得第 "+i+ "个连接. ");
newSocket=new   Socket(API_SERVER_HOST,API_SERVER_PORT);
self.socketPool.put(new   Integer(i),newSocket);
self.socketStatusArray[i]=true;
break;
}
}
catch(Exception   e)
{
System.out.println( "重建连接失败! ");
throw   new   RuntimeException(e);
}
}
return   newSocket;
}
public   synchronized   static   void   buildConnectionPool()
{
if(self==null)
init();

System.out.println( "准备建立连接池. ");
Socket   Socket=null;
try
{
for(int   i=0;i <CONNECTION_POOL_SIZE;i++)
{
Socket=new   Socket(API_SERVER_HOST,API_SERVER_PORT);
self.socketPool.put(new   Integer(i),Socket);
self.socketStatusArray[i]=false;
}
}
catch(Exception   e)
{
System.out.println( "与邮局得连接池建立失败! ");
throw   new   RuntimeException(e);
}
}

public   synchronized   static   void   releaseAllConnection()