c3p0 connection deadlock

 

c3p0 connection deadlock

 

 

      The author encountered the problem of c3p0 connection pool deadlock today. The deadlock of c3p0 is mostly related to the configuration file. If the c3p0 connection pool is set too small. When the connection pool is full. Since there is no priority set for individual threads. Causes the following thread to wait for the connection. cause deadlock.

       Solution: Set max_statements to 0.

      When c3p0 closes statement and connection at the same time, or when the time between closing them is very short, sometimes the connection is not closed because some preparedstatements are still cached.

       As a digression: a deadlock occurs when two users (or sessions) have locks on different objects, and each user needs a lock on the other object. Each user waits for the other user to release his lock. When two connections get stuck in deadlock, Microsoft? SQL Server? will be tested. One of the connections was chosen as the deadlock victim. The transaction for this connection is rolled back , and the application receives an error.

Deadlocks or blocking can also occur when using distributed transactions . Any lock-based concurrent system inevitably has characteristics that may block under certain circumstances. Blocking occurs when one connection controls a lock and another connection requires a conflicting lock type. The result is to force the second connection to wait, or to block on the first connection.
  The term "connection" refers to a single login session to a database. Each connection appears as a system process ID (SPID). Although each SPID is generally not a separate process context , it is often used here to refer to a process. Rather, each SPID consists of server resources and data structures that serve requests from a given client's single connection. A single client application may have one or more connections. As far as SQL Server is concerned, there is no difference between multiple connections from a single client application on a single client and multiple connections from multiple client applications or multiple clients. One connection can block the other, whether from the same application or from separate applications on two different clients. )

     

      The following code illustrates the detailed configuration parameters of the secondary c3p0:

 

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class ConnectionManager {

    private ComboPooledDataSource ds;
    private ConnectionManager connManger;

    private ConnectionManager() throws PropertyVetoException {
        ds = new ComboPooledDataSource();
        // Set the database driver class for the c3p0 connection pool
        ds.setDriverClass("com.mysql.jdbc.Driver");
        // Set the c3p0 connection pool database connection URL
        ds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/school");
        // Set the c3p0 connection pool database username
        ds.setUser("root");
        // Set the c3p0 connection pool database password
        ds.setPassword("root");
        // When the connections in the connection pool are used up, the number of new connections created by C3P0 at one time is 2
        ds.setAcquireIncrement(2);
        // acquireRetryAttempts: Defines the number of times to repeat the acquisition after a new connection fails to be acquired from the database, the default is 30 seconds
        ds.setAcquireRetryAttempts(30);
        // The interval between two connections, in milliseconds, the default is 1000;
        ds.setAcquireRetryDelay(3000);
        // By default all uncommitted operations are rolled back when the connection is closed. Default is false;
        ds.setAutoCommitOnClose(false);
        /**
         * C3P0 will create an empty table named Test and use its own query statement for testing. If this parameter is defined, the property preferredTestQuery will be ignored.
         * You can't do anything on this Test table, it will be used for C3P0 test, the default is null;
         */
        // ds.setAutomaticTestTable("teacher");
        /**
         * Failure to acquire a connection will cause all threads waiting to acquire a connection to throw an exception. However, the data source is still valid and will continue to try to obtain a connection the next time getConnection() is called. If set to true,
         * Then the data source will declare that it has been disconnected and permanently closed after the attempt to obtain the connection fails. Default is false;
         */
        ds.setBreakAfterAcquireFailure(false);
        /**
         * When the connection pool runs out, the client calls getConnection() and waits for a new connection to be obtained. After the timeout, an SQLException will be thrown. If it is set to 0, it will wait indefinitely. The unit is milliseconds, the default is 0;
         */
        ds.setCheckoutTimeout(1000);
        /**
         * Test the connection by implementing ConnectionTester or QueryConnectionTester class, the class name needs to be set to the fully qualified name. The default is
         * com.mchange.v2.C3P0.impl.DefaultConnectionTester;
         */
        ds.setConnectionTesterClassName(new DefaultConnectionTester().getClass().getName());
        // hook method, when operating on related resources, ''the connection he operates is a real database connection, not a proxy connection''
        // ds.setConnectionCustomizerClassName("");
        // connection pool data source
        // ds.setConnectionPoolDataSource(ConnectionPoolDataSource object);
        // idleConnectionTestPeriod: how many seconds to check idle connections in all connection pools, the default is 0, which means no check
        ds.setIdleConnectionTestPeriod(10);
        // The number of connections created during initialization, which should be between minPoolSize and maxPoolSize. The default is 3;
        ds.setInitialPoolSize(5);
        // Maximum idle time, connections that exceed the idle time will be discarded. 0 or negative to never discard. Default is 0;
        ds.setMaxIdleTime(3);
        // The maximum number of connections to keep in the connection pool. The default is 15;
        ds.setMaxPoolSize(100);
        /**
         * JDBC standard parameters to control the number of PreparedStatements loaded in the data source. But because the pre-cached Statement belongs to a single Connection rather than the entire connection pool.
         * So setting this parameter needs to consider many factors. If maxStatements and maxStatementsPerConnection are both 0, the cache is closed. Default is 0;
         */
        ds.setMaxStatements(1000);
        // The maximum number of cached Statements owned by a single connection in the connection pool. Default is 0;
        ds.setMaxStatementsPerConnection(100);
        // C3P0 operates asynchronously, and slow JDBC operations are done through helper processes. Extending these operations can effectively improve performance, enabling multiple operations to be executed simultaneously through multithreading. The default is 3;
        ds.setNumHelperThreads (5);
        /**
         * preferredTestQuery: Defines the test statement that all connection tests execute. This parameter can significantly increase the test speed in the case of using the connection test. The table under test must exist at the time of the initial data source. Defaults to null; propertyCycle:
         * The maximum number of seconds the user waits before modifying the system configuration parameters. The default is 300; testConnectionOnCheckout: Please use it only when needed due to high performance consumption. If set to true then every connection submits
         * Will check its validity. It is recommended to use methods such as idleConnectionTestPeriod or automaticTestTable to improve the performance of connection tests. Default is false;
         * testConnectionOnCheckin: If set to true, the validity of the connection will be checked while the connection is obtained. Defaults to false.
         *
         */
    }

    public static void main(String[] args) {

        try {
            ConnectionManager connManger = new ConnectionManager();
            Connection conn = connManger.ds.getConnection();
            Statement st = conn.createStatement();
            String sql = "select * from teacher";
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                System.out.println(rs.getInt("id") + "," + rs.getString("name"));
            }
        }
        catch (PropertyVetoException e) {
            e.printStackTrace ();
        }
        catch (SQLException e) {
            e.printStackTrace ();
        }

    }
}

 

Reference : Detailed explanation of CSDN c3p0 strength and parameters

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326613775&siteId=291194637