java

位置:IT落伍者 >> java >> 浏览文章

Java程序性能优化-对象复用“池”(2)[1]


发布日期:2019年09月30日
 
Java程序性能优化-对象复用“池”(2)[1]

对象复用

为了能够从代码层面更好地理解数据库连接池读者可以仔细阅读以下代码

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()

}

}

[] []

               

上一篇:Java程序性能优化-对象复用“池”(2)[2]

下一篇:Java程序性能优化-对象复用“池”(3)[2]