What is the close method of java. SQL. Connection? (take MySQL as an example), connectionclose

Source: Internet
Author: User

What is the close method of java. SQL. Connection? (take MySQL as an example), connectionclose

Reprinted please indicate the source:Http://blog.csdn.net/aheeoheehahee/article/details/42641601

I would like to send this article to a programmer who has the same research skills as me, hoping to help you ............

Let's talk about the code.

public static void main(String[] args) throws Exception {// TODO Auto-generated method stubClass.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/financial_db", "root", "admin");conn.close();System.out.println(conn.isClosed()); // true after conn.close() if no exceptionSystem.out.println(conn == null); // not null after conn.close()Connection emptyConn = null;emptyConn.isClosed(); // NullPointerException}

Explanation:

1. the java. SQL. Connection. close () method immediately releases the database connection resources occupied by the Connection object, instead of waiting for the JVM garbage collection mechanism to recycle it. The API says, link: http://docs.oracle.com/javase/7/docs/api/java/ SQL /Connection.html#close%28%29. Not as I thought, the close method will simply set the conn object to null. In fact, after calling close (), conn is still not null.

2. For a null connection, calling the close () method will report a null pointer exception.

With regard to the interpretation of the close () method, I was inspired by a few of the answers mentioned above: http://www.zhihu.com/question/20849384/answer/16382647

Of course, if you just want to know why to close a Connection and use the close method instead of directly setting it to null, or wait for it to be reclaimed by garbage collection, you can close the window here. If you are just like me and are interested in what the close method has done, please take a look at it.


What did this close method do? Well, I read the MySQL ctor/J code and then wrote:

Java. SQL. Connection itself is an interface, and how to implement it is implemented by JDBC itself. The implementation in MySQL is

1. Use the com. mysql. jdbc. Connection interface to inherit the java. SQL. Connection interface:

public interface Connection extends java.sql.Connection, ConnectionProperties

2. Use com. mysql. jdbc. MySQLConnection to inherit the com. mysql. jdbc. Connection interface:

public interface MySQLConnection extends Connection, ConnectionProperties

3. Use com. mysql. jdbc. ConnectionImpl to implement the com. mysql. jdbc. MySQLConnection interface:

public class ConnectionImpl extends ConnectionPropertiesImpl implements MySQLConnection

We assume that if you use MySQL Connector/J to connect to the MySQL database, you can use java. SQL. driverManager. getConnection (...) the Connection object obtained by the method should be of the com. mysql. jdbc. connectionImpl (it should be itself or its subclass ). code proof:

public static void main(String[] args) throws Exception {Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/financial_db", "root", "admin");System.out.println(conn instanceof com.mysql.jdbc.ConnectionImpl); // true}
The result is true, which is assumed to be true.

Find com. mysql. jdbc. the close onimpl close method is used in java programming. SQL. connection. the close () method is implemented in MySQL ctor/J as follows:

    /**     * In some cases, it is desirable to immediately release a Connection's     * database and JDBC resources instead of waiting for them to be     * automatically released (cant think why off the top of my head) <B>Note:</B>     * A Connection is automatically closed when it is garbage collected.     * Certain fatal errors also result in a closed connection.     *      * @exception SQLException     *                if a database access error occurs     */    public void close() throws SQLException {        synchronized (getConnectionMutex()) {            if (this.connectionLifecycleInterceptors != null) {                new IterateBlock<Extension>(this.connectionLifecycleInterceptors.iterator()) {                    @Override                    void forEach(Extension each) throws SQLException {                        ((ConnectionLifecycleInterceptor) each).close();                    }                }.doForAll();            }            realClose(true, true, false, null);        }    }

The official comment says this method is used when resources need to be released immediately. A connection is automatically closed when it is recycled, and some fatal errors (fatal errors) will also cause the connection to be closed.

Through the code, we can find that in the close method, the realClose method (the above ConnectionLifecycleInterceptor only finds one interface in the jdbc code) that truly releases the connection resource, it seems that the specific implementation is related to the MySQL attachment). The original Article says: implementors of this interface can be installed via the "connectionLifecycleInterceptors" configuration property and receive events and alter behavior of "lifecycle" methods on our connection implementation. (this interface can be installed through connectionLifecycleInterceptors configuration property. , Receiving time and changing the action of the lifecycle method in the connection implementation ). This is not the point. The point is the realClose below. The code is too long and I stick it to the end.

By reading the realClose code, we can find that this method has four parameters. The first three parameters are of the boolean type, and the fourth parameter is of the Throwable type. CalledExplicitly indicates whether the method is called from the close () method. issueRollback indicates whether the rollback operation rollback () is required when resources are released (). The last two parameters are not commented out, So skipLocalTeardown indicates whether to skip the local teardown (no valuable results are found on google ......), The reason is finally assigned to the forceClosedReason (Why was this connection implicitly closed, if known? (For diagnostics) Why is this connection closed implicitly? If the cause is known (used for diagnosis )). These two parameters have little to do with the problems we have studied. The realClose core code is as follows:

       try {            if (!skipLocalTeardown) { // part 1 starts                   // ......                try {                    <strong>closeAllOpenStatements();</strong>                } catch (SQLException ex) {                    sqlEx = ex;                } // part 1 ends                if (this.io != null) { // part 2 starts                    try {                        <strong>this.io.quit();</strong>                    } catch (Exception e) {                    }                }            } else {                <strong>this.io.forceClose();</strong>            } // part 2 ends            if (this.statementInterceptors != null) { // part 3 starts                for (int i = 0; i < this.statementInterceptors.size(); i++) {                    this.statementInterceptors.get(i).destroy();                }            }            if (this.exceptionInterceptor != null) {                this.exceptionInterceptor.destroy();            } // part 3 ends        } finally {            // part 4 starts            this.openStatements = null;            if (this.io != null) {                <strong>this.io.releaseResources();</strong>                this.io = null;            }            this.statementInterceptors = null;            this.exceptionInterceptor = null;            <strong>ProfilerEventHandlerFactory.removeInstance(this);</strong>            synchronized (getConnectionMutex()) {                if (this.cancelTimer != null) {                    <strong>this.cancelTimer.cancel();</strong>                }            }            <strong>this.isClosed = true;</strong>            // part 4 ends         }     }
Commented out in the code,

Part 1 closes all open statements in the connection through the closeAllIOpenStatements method,

Part 2 is used to close the connection IO (through the quit or forceClose method ),

Part 3 declares the interceptor (statement interceptor) and exception interceptor Used to destroy (destroy) connections ),

Part 4: Set the closed openStatements, IO (if the IO is not null, release the resource using the releaseResources method), statementInterceptors, and exceptionInterceptor to null, delete the ProfilerEventHandler corresponding to the connection (this class is a single interface in the jdbc source code without corresponding comments) and cancel the cancelTimer timer of the connection, set the connected isClosed attribute to true (the isClosed method shown in the Code returns the value of this attribute ).

Therefore, through the code, we can see what resources need to be applied for when MySQL JDBC creates a connection. As for the usage of these resources, I will study it again, I will continue to explain it to you later. Pai_^

I found myself crying T_T after writing it here,If the close method only sets the Connection to null, how can I call the isClosed method?? Alas, too young too naive has been turning around for so long. T_T

However, by reading the code, we found that the realclose method sets the reference of the released resource object to null. This is an inspiration. after calling the close method for connection, then, set it to null to avoid forgetting that the connection has been closed and cannot be used (because NullPointerException will be used directly), which reduces the potential bug risks. In short, after reading the code, the gains are quite high. As many foreign colleagues around us say, our domestic programmers are reluctant to share their gains and gains with you. Well, I have written it all here. Thank you for handing me the ice cream roommate. Let's see you next time. Cya.


The complete source code of com. jdbc. mysql. ConnectionImpl. realClose method is provided. If you are interested, you can study it together. Haha:

    /**     * Closes connection and frees resources.     *      * @param calledExplicitly     *            is this being called from close()     * @param issueRollback     *            should a rollback() be issued?     * @throws SQLException     *             if an error occurs     */    public void realClose(boolean calledExplicitly, boolean issueRollback, boolean skipLocalTeardown, Throwable reason) throws SQLException {        SQLException sqlEx = null;        if (this.isClosed()) {            return;        }        this.forceClosedReason = reason;        try {            if (!skipLocalTeardown) {                if (!getAutoCommit() && issueRollback) {                    try {                        rollback();                    } catch (SQLException ex) {                        sqlEx = ex;                    }                }                reportMetrics();                if (getUseUsageAdvisor()) {                    if (!calledExplicitly) {                        String message = "Connection implicitly closed by Driver. You should call Connection.close() from your code to free resources more efficiently and avoid resource leaks.";                        this.eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_WARN, "", this.getCatalog(), this.getId(), -1, -1, System                                .currentTimeMillis(), 0, Constants.MILLIS_I18N, null, this.pointOfOrigin, message));                    }                    long connectionLifeTime = System.currentTimeMillis() - this.connectionCreationTimeMillis;                    if (connectionLifeTime < 500) {                        String message = "Connection lifetime of < .5 seconds. You might be un-necessarily creating short-lived connections and should investigate connection pooling to be more efficient.";                        this.eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_WARN, "", this.getCatalog(), this.getId(), -1, -1, System                                .currentTimeMillis(), 0, Constants.MILLIS_I18N, null, this.pointOfOrigin, message));                    }                }                try {                    closeAllOpenStatements();                } catch (SQLException ex) {                    sqlEx = ex;                }                if (this.io != null) {                    try {                        this.io.quit();                    } catch (Exception e) {                    }                }            } else {                this.io.forceClose();            }            if (this.statementInterceptors != null) {                for (int i = 0; i < this.statementInterceptors.size(); i++) {                    this.statementInterceptors.get(i).destroy();                }            }            if (this.exceptionInterceptor != null) {                this.exceptionInterceptor.destroy();            }        } finally {            this.openStatements = null;            if (this.io != null) {                this.io.releaseResources();                this.io = null;            }            this.statementInterceptors = null;            this.exceptionInterceptor = null;            ProfilerEventHandlerFactory.removeInstance(this);            synchronized (getConnectionMutex()) {                if (this.cancelTimer != null) {                    this.cancelTimer.cancel();                }            }            this.isClosed = true;        }        if (sqlEx != null) {            throw sqlEx;        }    }




Related Article

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.