PackageCom.demo.myDataSource;Importjava.sql.Connection;Importjava.util.LinkedList;ImportJavax.sql.DataSource;Importcom.demo.jdbc.jdbcUtils;/** * @authorAdministrator * Custom connection pooling*/ Public classmyDataSource {//Create a collection as a pool for storing connection objects StaticLinkedlist<connection> pool =NewLinkedlist<connection>(); Static{ //Initialize connection pool (default initialization 3) for(inti = 0;i<3;i++) {Connection conn; Try{conn=jdbcutils.getconnection (); POOL.ADDLAST (conn); } Catch(Exception e) {e.printstacktrace (); } } } //Get Connections Public StaticConnection getconnection () {//take a connection connection object from the Pool collection if(Pool.isempty ()) {//If the pool is empty, add 2 additional connection objects for(inti = 0;i<2;i++) {Connection conn; Try{conn=jdbcutils.getconnection (); POOL.ADDLAST (conn); } Catch(Exception e) {e.printstacktrace (); }}} System.out.println ("Connection objects obtained from the connection pool"); //is not empty, the first connection object is returned returnPool.removefirst (); } //Release connection (return connection) Public Static voidreleaseconnection (Connection conn) {pool.addlast (conn); System.out.println ("Connection has been returned"); } }
PackageCom.demo.myDataSource;Importjava.sql.Connection;Importjava.util.LinkedList;ImportJavax.sql.DataSource;Importcom.demo.jdbc.jdbcUtils;/** * @authorAdministrator * Custom connection pooling*/ Public classmyDataSource {//Create a collection as a pool for storing connection objects StaticLinkedlist<connection> pool =NewLinkedlist<connection>(); Static{ //Initialize connection pool (default initialization 3) for(inti = 0;i<3;i++) {Connection conn; Try{conn=jdbcutils.getconnection (); POOL.ADDLAST (conn); } Catch(Exception e) {e.printstacktrace (); } } } //Get Connections Public StaticConnection getconnection () {//take a connection connection object from the Pool collection if(Pool.isempty ()) {//If the pool is empty, add 2 additional connection objects for(inti = 0;i<2;i++) {Connection conn; Try{conn=jdbcutils.getconnection (); POOL.ADDLAST (conn); } Catch(Exception e) {e.printstacktrace (); }}} System.out.println ("Connection objects obtained from the connection pool"); //is not empty, the first connection object is returned returnPool.removefirst (); } //Release connection (return connection) Public Static voidreleaseconnection (Connection conn) {pool.addlast (conn); System.out.println ("Connection has been returned"); } }
Custom simple JDBC Connection pooling and testing