Simple database connection Pool instance (Java language)

Source: Internet
Author: User

1. Overview

Frequent creation and destruction of database connections consumes very much system resources, creates a pool, manages a certain number of connections, uses the time to go to the pool, and puts it back into the pool, which is a more general practice.

2. Keywords

LinkedList synchronized Invocationhandler Countdownlatch

3. Code

3.1 Connectionpool.java

 PackageCom.rocky.pool;Importjava.sql.Connection;Importjava.util.LinkedList; Public classConnectionPool {PrivateLinkedlist<connection> pool =NewLinkedlist<connection>();  PublicConnectionPool (intinitialsize) {        if(InitialSize > 0){             for(inti=0; i<initialsize; i++) {pool.addlast (connectiondriver.createconection ()); }        }    }         Public voidreleaseconnection (Connection Connection) {if(Connection! =NULL){            synchronized(pool) {//notify when the connection is released so that other consumers can perceive that a connection has been returned in the poolPool.addlast (connection);//Pool.notifyall ();// AllPool.notify ();// All                            }        }    }         PublicConnection Fetchconnection (LongMillsthrowsinterruptedexception{synchronized(pool) {//timed out            if(Mills <= 0){                 while(Pool.isempty ()) {pool.wait (); }                returnPool.removefirst (); }Else{                LongFuture = System.currenttimemillis () +Mills; LongRemaining =Mills;  while(Pool.isempty () && remaining >0) {pool.wait (remaining); Remaining= Future-System.currenttimemillis (); } Connection result=NULL; if(!Pool.isempty ()) {Result=Pool.removefirst (); }                returnresult; }        }            }}

3.2 Connectiondriver.java

 PackageCom.rocky.pool;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;Importjava.sql.Connection; Public classConnectiondriver {Static classConnectionhandlerImplementsinvocationhandler{@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {if(Method.getname (). Equals ("Commit") {thread.sleep (1000); }            return NULL; }    }        //Create a connection proxy     Public StaticConnection createconection () {return(Connection) Proxy.newproxyinstance (Connectiondriver.class. getClassLoader (),NewClass<?>[]{connection.class},NewConnectionhandler ()); } }

3.3 Connectionpooltest.java

 PackageCom.rocky.pool;Importjava.sql.Connection;Importjava.sql.SQLException;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.atomic.AtomicInteger; Public classConnectionpooltest {StaticConnectionPool pool =NewConnectionPool (10); //ensure all runner can run simultaneously    StaticCountdownlatch start =NewCountdownlatch (1); StaticCountdownlatch end;  Public Static voidMain (string[] args)throwsException {intThreadCount = 20; End=NewCountdownlatch (ThreadCount); intCount = 20; Atomicinteger got=NewAtomicinteger (); Atomicinteger Notgot=NewAtomicinteger ();  for(inti=0; i<threadcount; i++) {thread thread=NewThread (NewConnectionrunner (count, got, Notgot), "Conectionrunnerthread" +i);        Thread.Start ();        } start.countdown ();        End.await (); System.out.println ("Total Invoke:" + (threadcount) *count); System.out.println ("Got connection:" +got); System.out.println ("Not got Connection" +notgot); }        Static classConnectionrunnerImplementsrunnable{intcount;        Atomicinteger got;        Atomicinteger Notgot;  PublicConnectionrunner (intcount, Atomicinteger got, Atomicinteger Notgot) {             This. Count =count;  This. got =got;  This. Notgot =Notgot; } @Override Public voidrun () {Try{start.await (); } Catch(interruptedexception e) {e.printstacktrace (); }             while(Count > 0){                Try{Connection Connection= Pool.fetchconnection (1000); if(Connection! =NULL){                        Try{connection.createstatement ();                        Connection.commit (); }finally{pool.releaseconnection (connection);                        Got.incrementandget (); }                    }Else{notgot.incrementandget (); }                } Catch(Interruptedexception |SQLException e)                {E.printstacktrace (); }finally{Count--;        }} end.countdown (); }            }    }

3.4 Description

By changing the number of threadcount in the main method, you can see that as the number of threads increases, the percentage of connection hits is decreasing,

The client thread waits and times out to return because the number of connections in the connection pool must be (10).

Simple database connection Pool instance (Java language)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.