2017-02-24 71 views
0

我添加到連接ArrayList和歌廳逐一連接,當我需要使用它們,這裏我使用的是從連接池連接,如何在使用連接池後返回連接時檢查連接是否有效?

ArrayList<Connection> al=new ArrayList<Connection>(); 

public Connection getconnection(){ 
    if(al.size()>0) 
    { 
     try{ 
      connection = al.get(0); 
      al.remove(connection); 
      }catch(Exception e){ 
      out.print(e); 
      } 
    }else{ 
     out.println("No Database connection is Available !"); 
    } 
    return connection; 
} 

使用此連接後,我回到回連接池。

public void returnconnection(Connection con){ 
    Connection c = con; 
    al.add(c); 
    out.println("Hi I'm Connection, I'm back! "); 
} 

在這裏我需要檢查這個連接是否存在或沒有添加到ArrayList之前?

+0

是[這](http://stackoverflow.com/a/7764708/2815219)有用嗎? –

+0

請勿扮演您自己的連接池。使用現有的像HikariCP,DBCP,c3p0等,它會爲您節省很多頭痛和錯誤。 –

回答

0

找到了這一問題的解決,希望這會有所幫助,

//checking connection is live or not 
public boolean checkconnection(Connection conn){ 
    Connection validconnection = conn; 
    try{ 
     if(validconnection.isValid(1) && validconnection !=null) 
     return true; 
    }catch(Exception er){ 
     out.println("\n I'm not valid connection I can be null or Invalid, Please Check!"); 
    } 
    return false; 
} 
//Adding Connection back to pool 
public void returnconnection(Connection con) throws Exception{ 
    Connection c = con; 
    boolean validreturncon=checkconnection(c); 
    if (validreturncon){ 
     al.add(c); 
     out.println("Hi I'm Connection, I'm back! "); 
    } 
    else{ 
     out.println("\n Dead Connection, No need to put me into ArrayList! "); 
    } 
}