How Java gracefully shuts down resources

Source: Internet
Author: User

In real-world development, it is often necessary to open some physical resources in the program, such as database connection, network connection, disk file, etc., after opening these physical resources must be explicitly closed, otherwise it will cause resource leaks.

The garbage collection mechanism of the JVM does not reclaim these resources, the garbage collection mechanism is part of Java memory Management, it is only responsible for reclaiming the memory allocated in the heap memory, as for the physical resources opened in the program, garbage collection mechanism is powerless.

In order to gracefully close the physical resources that are open in the program, you should use the Finally block to guarantee recycling.

The following procedure demonstrates common database resources.

Importjava.sql.Connection;

Importjava.sql.DriverManager;

Importjava.sql.PreparedStatement;

Importjava.sql.ResultSet;

Importjava.sql.SQLException;

public class Tester {

public static void Main (string[] args) {

String url = "Jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "root";

Connection conn = null;

PreparedStatement PST = NULL;

ResultSet rs = null;

try {

Class. forname ("Com.mysql.jdbc.Driver");

conn = DriverManager. getconnection (url,user, password);

PST = Conn.preparestatement ("select* from Test");

rs = Pst.executequery ();

while (Rs.next ()) {

System. out. println (rs.getobject (0));

}

} catch (ClassNotFoundException e) {

E.printstacktrace ();

} catch (SQLException e) {

E.printstacktrace ();

} finally {

try {

Rs.close ();

Pst.close ();

Conn.close ();

} catch (SQLException e) {

E.printstacktrace ();

}

}

}

}

Although the program has used the finally block to ensure that resources are closed, the shutdown of this program is not secure. Since the program starts with specifying conn = Null;pst = Null;rs = null, it is entirely possible that the exception was thrown before the Conn was initialized during the program's run, so Conn, PST, and RS did not have time to initialize, so they did not need to be shut down at all.

Change the above procedure to the following form:

Importjava.sql.Connection;

Importjava.sql.DriverManager;

Importjava.sql.PreparedStatement;

Importjava.sql.ResultSet;

Importjava.sql.SQLException;

public class Tester {

public static void Main (string[] args) {

String url = "Jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "root";

Connection conn = null;

PreparedStatement PST = NULL;

ResultSet rs = null;

try {

Class. forname ("Com.mysql.jdbc.Driver");

conn = DriverManager. getconnection (url,user, password);

PST = Conn.preparestatement ("select* from Test");

rs = Pst.executequery ();

while (Rs.next ()) {

System. out. println (rs.getobject (0));

}

} catch (ClassNotFoundException e) {

E.printstacktrace ();

} catch (SQLException e) {

E.printstacktrace ();

} finally {

try {

if (rs! = null) {

Rs.close ();

}

if (PST! = null) {

Pst.close ();

}

IF (conn! = null) {

Conn.close ();

}

} catch (SQLException e) {

E.printstacktrace ();

}

}

}

}

The program first save RS is not NULL to close, and then ensure that the PST is not NULL to close the PST, and then ensure that Conn is not NULL to close Conn.

This looks safe on the surface, which is actually not the case. If the program began to properly initialize the conn, PST, RS, the close of the RS when there is an exception, then the program will close the RS when the abnormal exit, which will lead to PST, Conn is not closed, resulting in a resource leak.

To ensure that exceptions that occur when you close each resource do not affect each other, you should use the Try...catch block separately when closing each resource to ensure that the shutdown does not cause the program to exit abnormally.

Importjava.sql.Connection;

Importjava.sql.DriverManager;

Importjava.sql.PreparedStatement;

Importjava.sql.ResultSet;

Importjava.sql.SQLException;

public class Tester {

public static void Main (string[] args) {

String url = "Jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "root";

Connection conn = null;

PreparedStatement PST = NULL;

ResultSet rs = null;

try {

Class. forname ("Com.mysql.jdbc.Driver");

conn = DriverManager. getconnection (url,user, password);

PST = Conn.preparestatement ("select* from Test");

rs = Pst.executequery ();

while (Rs.next ()) {

System. out. println (rs.getobject (0));

}

} catch (ClassNotFoundException e) {

E.printstacktrace ();

} catch (SQLException e) {

E.printstacktrace ();

} finally {

if (rs! = null) {

try {

Rs.close ();

} catch (SQLException e) {

E.printstacktrace ();

}

}

if (PST! = null) {

try {

Pst.close ();

} catch (SQLException e) {

E.printstacktrace ();

}

}

IF (conn! = null) {

try {

Conn.close ();

} catch (SQLException e) {

E.printstacktrace ();

}

}

}

}

}

The above program shows that the resource shutdown method is relatively safe, this closure method is mainly guaranteed by the following 3 points:

1. Use the finally block to close the physical resource and ensure that the close operation is always performed;

2. First ensure that reference variables referencing the resource are not NULL before closing each resource;

3. Use a separate Try...catch block for each physical resource to close the resource, guaranteeing that the exception thrown when the resource is closed does not affect the shutdown of other resources.

Reprint: http://blog.csdn.net/leaderman_it/article/details/7445491

How Java gracefully shuts down resources

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.