熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java程序性能優化-對象復用“池”(2)[1]

2013-11-23 20:00:30  來源: Java高級技術 

    對象復用

  為了能夠從代碼層面更好地理解數據庫連接池讀者可以仔細閱讀以下代碼

  public static void main(String[] argv) {

  try {

  ClassforName(commysqljdbcDriver

  DataSource unpooled = DataSources

  unpooledDataSource(

  jdbc:mysql://:/test

  root

  DataSource pooled = DataSourcespooledDataSource(unpooled)

  Connection con = null;

  Statement stmt = null;

  ResultSet rs = null;

  con = pooledgetConnection()       //第一次取得數據庫連接

  Systemoutprintln(con Class Type is:+congetClass()getName())

  Object o=getInnter(con)           //取得內部的實際數據庫連接

  Systemoutprintln(Inner con Class Type is:+ogetClass()

  getName())

  stmt = concreateStatement()

  rs = stmtexecuteQuery(SELECT * FROM user

  while (rsnext())

  Systemoutprintln(Data from DB:+rsgetString())

  rsclose()

  stmtclose()

  conclose()

  Threadsleep(                 //等待連接返回池中

  con = pooledgetConnection()       //第二次取得數據庫連接

  Object o=getInnter(con)

  if(o==o)                          //相同則說明數據庫連接被復用

  Systemoutprintln(o and o is same object

  stmt = concreateStatement()

  rs = stmtexecuteQuery(SELECT * FROM user

  while (rsnext())

  Systemoutprintln(Data from DB:+rsgetString())

  rsclose()

  stmtclose()

  conclose()

  } catch (Exception e) {

  eprintStackTrace()

  }

  }

[]  []  


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27799.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.