2014-01-20 61 views
0

我正在使用java servlet/jsp構建。我有一個類來處理數據庫連接,但我不知道應該爲每個請求創建每個實例或爲所有請求創建一個實例。 例如:是否應爲每個請求創建新實例?

方案1

class HandleDB { 
    public static HandleDB getInstance(); // singleton pattern 
    public void initConnection(); 
    public void releaseConnection(); 
} 

然後,

//at the beginning of a request: 
HandleDB.getInstance().initConnection(); 
// handle tasks 
// at the end of request 
HandleDB.getInstance().releaseConnection(); 

方案2

class HandleDB { 
    public void initConnection(); 
    public void releaseConnection(); 
} 

//at the beginning of a request: 
HandleDB db = new HandleDB(); 
db.initConnection(); 
// handle tasks 
// at the end of request 
db.releaseConnection(); 
db = null; 

哪種情況應PRA使用ctice?

回答

1

與方案2一起使用。方案1的問題是相同的HandleDB實例將被所有請求共享,並且可能導致線程安全問題。請記住,請求可以並行執行。標準是每個線程/請求都有一個連接。

大多數Web應用程序使用連接池(如C3P0或Apache DBCP)來避免必須爲每個請求創建新連接。您在請求開始時從池中獲得連接,並在請求結束時將其返回給池,以便其他請求稍後可以重用。

+0

是的,我們使用Apache DBCP連接池,我會爲你的建議。 – ipkiss

0

使用監聽器LINK

public class AppServletContextListener implements ServletContextListener{ 

    @Override 
    public void contextDestroyed(ServletContextEvent arg0) { 
        /// Destroy DB Connection 
    } 

    @Override 
    public void contextInitialized(ServletContextEvent arg0) { 
        /// Create DB Connection 
    } 
} 
0

,如果您有批量的任務,你應該創建僅在第一個任務開始的數據庫連接的再整理你應該釋放所有任務或免費數據庫連接

爲後您的案例場景1適用。

相關問題