连接池 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7127268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:44:16  来源:igfitidea点击:

Connection Pool Java

javaconnectionpool

提问by user830818

Here is a ConnectionPool that i implemented. Is it a good design to have all variables and methods as static. Please explain why or why not

这是我实现的 ConnectionPool。将所有变量和方法设为静态是否是一个好的设计。请解释为什么或为什么不

public class MyCp1 {

    private static final int MAX_SIZE=100;
    private static final BlockingQueue<Connection> bq;

    static{
         System.out.println("Inside begin static block" );
        bq= new ArrayBlockingQueue<Connection>(MAX_SIZE);
        for(int i=0;i<MAX_SIZE;i++)
        {
            try {
                try {
                    bq.put(makeConnection());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        System.out.println("total size:" + bq.size());
    }

    public static Connection getConnection() throws InterruptedException
    {
        System.out.println("size before getting connection "+ bq.size()+ "  Thread name  "+ Thread.currentThread().getName());
        Connection con=bq.take();
        System.out.println("size after getting connection  "+ bq.size()+"  Thread name  "+ Thread.currentThread().getName());
        return (con);
    }

    public static boolean releaseConnection(Connection con) throws InterruptedException
    {
        System.out.println("size before releasing connection  "+ bq.size()+" Thread name  "+ Thread.currentThread().getName());
        boolean bool =bq.add(con);
        System.out.println("size after releasing connection  "+ bq.size()+"  Thread name  "+ Thread.currentThread().getName());
        return (bool);
    }

    public static Connection makeConnection() throws SQLException {
        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", "root");
        connectionProps.put("password", "java33");
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        conn = DriverManager.getConnection("jdbc:" + "mysql" + "://"
                + "localhost" + ":" + "3306" + "/test", connectionProps);

        System.out.println("Connected to database");
        return conn;
    }


}

I know there are issues with exceptional handling and others, but i would appreciate if you can please stick to the above mentioned question

我知道存在特殊处理和其他问题,但如果您能坚持上述问题,我将不胜感激

EDIT::

编辑::

It looks like using static is not favored. So I refactored as much as i could to get rid of static. While this works, not sure if this is good design

看起来不喜欢使用静态。所以我尽可能地重构以摆脱静态。虽然这有效,但不确定这是否是好的设计

 public class ConnectionPool {

    private static final int MAX_SIZE = 100;
    private    BlockingQueue<Connection> bq;
    private static ConnectionPool cp= new ConnectionPool();


    private ConnectionPool(){
        System.out.println("inside constructor");
         bq = new ArrayBlockingQueue<Connection>(MAX_SIZE);
        Properties connectionProps = new Properties();
        connectionProps.put("user", "root");
        connectionProps.put("password", "java33");
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for (int i = 0; i < MAX_SIZE; i++) {
            try {
                bq.put(makeConnection(connectionProps));
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        System.out.println("total size:" + bq.size());
    }
    public static ConnectionPool getInstance()
    {
        return cp;

    }

    public  Connection getConnection() throws InterruptedException {
        System.out.println("size before getting connection" + bq.size());
        Connection con = bq.take();
        System.out.println("size after getting connection" + bq.size());
        return (con);
    }

    public  void releaseConnection(Connection con)
            throws InterruptedException {
        System.out.println("size before releasing connection" + bq.size());
         bq.put(con);
        System.out.println("size after releasing connection" + bq.size());
        //return (bool);
    }

    private  Connection makeConnection(Properties connectionProps) throws SQLException {
        Connection conn = null;
        conn = DriverManager.getConnection("jdbc:" + "mysql" + "://"
                + "localhost" + ":" + "3306" + "/test", connectionProps);

        System.out.println("Connected to database");
        return conn;
    }

}

回答by Reverend Gonzo

Absolutely not. What you have is more of an object recycler, which is fine if that's what you need.

绝对不。您拥有的更多是一个对象回收器,如果这是您需要的,那很好。

(As a recycler, however, you still don't want static fields, but you'd just create one instance of the recycler.)

(然而,作为回收者,您仍然不需要静态字段,但您只需创建回收者的一个实例。)

For a connection pool (and if this for something like JDBC Connections) it needs to be thread-safe, and ideally you shouldn't need to return the connection.

对于连接池(如果是 JDBC Connections 之类的),它需要是线程安全的,理想情况下您不需要返回连接。

Connection pools that are thread-safe will use ThreadLocalto return a connection that will only ever be used on that thread. If one is not available, it will then create a new connection by implementing ThreadLocal.initialValue().

线程安全的连接池将使用ThreadLocal返回一个仅在该线程上使用的连接。如果一个不可用,它将通过实现ThreadLocal.initialValue()创建一个新连接。

Furthermore, your threads should be created using an ExecutorService) so you reuse threads as well.

此外,您的线程应该使用ExecutorService创建),以便您也可以重用线程。