简体   繁体   中英

How to use connection pooling

I am new in connection pooling.I have a created a connection pool in mysql that adds five connections.Now i want to know what is the application of connection pooling,ie after creating that pool how to use that.. i am pasting my code here

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

import com.mysql.jdbc.Connection;

class ConnectionPoolManager {

String databaseUrl = "jdbc:mysql://localhost:3306/homeland";
String userName = "root";
String password = "root";

Vector connectionPool = new Vector();

public ConnectionPoolManager() {
    initialize();
}

public ConnectionPoolManager(
// String databaseName,
        String databaseUrl, String userName, String password) {
    this.databaseUrl = databaseUrl;
    this.userName = userName;
    this.password = password;
    initialize();
}

private void initialize() {
    // Here we can initialize all the information that we need
    initializeConnectionPool();
}

private void initializeConnectionPool() {
    while (!checkIfConnectionPoolIsFull()) {
        System.out
                .println("Connection Pool is NOT full. Proceeding with adding new connections");
        // Adding new connection instance until the pool is full
        connectionPool.addElement(createNewConnectionForPool());
    }
    System.out.println("Connection Pool is full.");
}

private synchronized boolean checkIfConnectionPoolIsFull() {
    final int MAX_POOL_SIZE = 5;

    // Check if the pool size
    if (connectionPool.size() < 5) {
        return false;
    }

    return true;
}

// Creating a connection
private Connection createNewConnectionForPool() {
    Connection connection = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = (Connection) DriverManager.getConnection(databaseUrl,
                userName, password);
        System.out.println("Connection: " + connection);
    } catch (SQLException sqle) {
        System.err.println("SQLException: " + sqle);
        return null;
    } catch (ClassNotFoundException cnfe) {
        System.err.println("ClassNotFoundException: " + cnfe);
        return null;
    }

    return connection;
}

public synchronized Connection getConnectionFromPool() {
    Connection connection = null;

    // Check if there is a connection available. There are times when all
    // the connections in the pool may be used up
    if (connectionPool.size() > 0) {
        connection = (Connection) connectionPool.firstElement();
        connectionPool.removeElementAt(0);
    }
    // Giving away the connection from the connection pool
    return connection;
}

public synchronized void returnConnectionToPool(Connection connection) {
    // Adding the connection from the client back to the connection pool
    connectionPool.addElement(connection);
}

public static void main(String args[]) {
    new  ConnectionPoolManager();
}

}

can any one help?

The purpose of connection pooling is to maintain a number of open connections to a database so that when your application requires a connection it does not have to go through the potentially resource and time intensive process of opening a new connection.

When an application requires a database connection it 'borrows' one from the pool. When it's done, it gives it back and that connection may be reused at some later point.

Once you have obtained a connection, you use it in your application through the JDBC (Java Database Connectivity) API.

Oracle's basic tutorial for using JDBC can be found at http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html

Another thing to keep in mind is that alot of work has gone into developing connection pools already, and it probably is not necessary to reinvent the wheel, except perhaps as a learning excercise. Apache Tomcat's connection pool implementation can be used outside of Tomcat (for example, in a standalone Java application) and is fairly flexible and easy to configure. It can be found at https://people.apache.org/~fhanik/jdbc-pool/jdbc-pool.html

I would say the code is pretty self explanatory.

You create an instance of the pool, personally, I prefer to use a singleton, but that's another topic

ConnectionPoolManager connectionPoolManager = new  ConnectionPoolManager();

Now, every body that wants a connection, is going to need a reference to this manager. When you need to, you request a free connection from the pool...

public void queryDatabaseForStuff(ConnectionPoolManager cpm) throws SQLException {
    Connection con = cpm.getConnectionFromPool();
    //....

Once you're finished with the connection, you pass it back to the manager...

 try {
     //...
 } finally {
     cmp.returnConnectionToPool(con);
 }

Now. You might like to investigating a blocking process that will block the current call to getConnectionFromPool while the pool is empty, meaning that it will either throw an exception (if you want to include a time out feature) or a valid connection.

When re-pooling a Connection , you might like to check to see if the Connection has been closed or not and have some kind of revival process to ensure that the pool is awlays close to capcaity...

Please check this link for getting detailed answer - https://examples.javacodegeeks.com/core-java/sql/jdbc-connection-pool-example/

You don't need to recreate your Connection object pool , instead please use the libraries provided by Apache . Please be clear of the following : 1 - Why and what made you think of connection pool ? 2 - Use the following Apache commons-dbcp lib in your Maven project and then use the classes as per documentation . 3. Does this solve all your problems ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM