连接池实现原理
自己写一个线程池
public class OraclePool {
private static volatile OraclePool pool;
private OracleDataSource ds;
private Map<Connection,Boolean> map;
private String url= "jdbc:oracle:thin:@127.0.0.1:1521:orcl" ;
private String username= "lmdc461";
private String password= "lmdc";
private int initPoolSize=10;
private int maxPoolSize=200;
private int waitTime=100;
public OraclePool(){
init();
}
public static OraclePool getInstance(){
if ( pool== null) {
synchronized (OraclePool. class) {
pool= new OraclePool();
}
}
return pool;
}
private void init(){
try {
ds= new OracleDataSource();
ds.setURL( url);
ds.setUser( username);
ds.setPassword( password);
//ds.set
ds.setLoginTimeout(2000);
map= new HashMap<Connection, Boolean>();
for ( int i = 0; i < initPoolSize; i++) {
map.put(getNewConnection(), true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getNewConnection(){
try {
return ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public synchronized Connection getConnection(){
Connection conn= null;
try {
for (Entry<Connection,Boolean> entry : map.entrySet()) {
if ( entry.getValue()) {
conn= entry.getKey();
map.put( entry.getKey(), false);
break;
}
}
if ( conn== null) {
if ( map.size()< maxPoolSize) {
conn=getNewConnection();
map.put( conn, false);
} else{
wait( waitTime);
conn=getConnection();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public void releaseConnection(Connection conn){
if ( conn== null) {
return ;
}
try {
if ( map.containsKey( conn)) {
if ( conn.isClosed()) {
map.remove( conn);
} else{
if (! conn.getAutoCommit()) {
conn.setAutoCommit( true);
}
map.put( conn, true);
}
} else{
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用:
public class TestOraclePool {
private static volatile int a;
private synchronized static void incr(){
a++;
}
public static void main(String[] args) throws InterruptedException{
int times=10;
System. out.println( "start``````````");
long start=System. currentTimeMillis();
for ( int i = 0; i < times; i++) {
new Thread( new Runnable(){
@Override
public void run() {
OraclePool pool= new OraclePool();
Connection conn= pool.getConnection();
Statement stmt= null;
ResultSet rs= null;
try {
stmt= conn.createStatement();
rs= stmt.executeQuery( "select * from gd_user");
while ( rs.next()) {
System. out.println( "recordid:"+ rs.getString( "recordid")+
";username:"+ rs.getString( "username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally{
incr();
if ( rs!= null) {
try {
rs.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
if ( stmt!= null) {
try {
stmt.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
pool.releaseConnection( conn);
}
}
}).start();
}
while ( true){
if ( a== times) {
System. out.println( "finished,time:"+
(System. currentTimeMillis()-start));
break;
}
Thread. sleep(1000);
}
}
}