java:所有线程终止后关闭连接

标签 java methods call finalize

以下是我的类代码

import java.net.*;
import java.util.*;
import java.sql.*;
import org.apache.log4j.*;
class Database {
    private Connection conn;
    private org.apache.log4j.Logger log ;
    private static Database dd=new Database();
    private Database(){
        try{
            log= Logger.getLogger(Database.class);
            Class.forName("com.mysql.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://localhost/bc","root","root");
            conn.setReadOnly(false);
            conn.setAutoCommit(false);
            log.info("Datbase created");
            /*Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            conn=DriverManager.getConnection("jdbc:odbc:rmldsn");
            conn.setReadOnly(false);
            conn.setAutoCommit(false);*/

        }
        catch(Exception e){
            log.info("Cant Create Connection");
        }
    }
    public static Database getDatabase(){
        return dd;
    }
    public Connection getConnection(){
        return conn;
    }
    @Override
    protected void finalize()throws Throwable {
        try{
        conn.close();
        Runtime.getRuntime().gc();
        log.info("Database Close");
        }
        catch(Exception e){
            log.info("Cannot be closed Database");
        }
        finally{
            super.finalize();
        }        
    }
}

只能通过 getDatabase() 方法初始化数据库对象。下面是 4 个线程使用单个数据库连接的程序。

public class Main extends Thread {
    public static int c=0;
    public static int start,end;
    private int lstart,lend;
    public static Connection conn;
    public static Database dbase;
    public Statement stmt,stmtEXE; public ResultSet rst;
    /**
     * @param args the command line arguments
     */
    static{        
        dbase=Database.getDatabase();
        conn=dbase.getConnection();
    }
    Main(String s){
        super(s);
        try{
        stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);
       start=end;
       lstart=start;
       end=end+5;
       lend=end;
        System.out.println("Start -" +lstart +" End-"+lend);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run(){
       try{

            URL url=new URL("http://localhost:8084/TestWeb/");


    rst=stmt.executeQuery("SELECT * FROM bc.cdr_calltimestamp limit "+lstart+","+lend);

        while(rst.next()){

        try{
            rst.updateInt(2, 1);
            rst.updateRow();
            conn.commit();
            HttpURLConnection httpconn=(HttpURLConnection) url.openConnection();
            httpconn.setDoInput(true);
            httpconn.setDoOutput(true);
            httpconn.setRequestProperty("Content-Type", "text/xml");
            //httpconn.connect();

            String reqstring="<?xml version=\"1.0\" encoding=\"US-ASCII\"?>"+
                "<message><sms type=\"mt\"><destination messageid=\"PS0\"><address><number" +
                "type=\"international\">"+ rst.getString(1) +"</number></address></destination><source><address>" +
                "<number type=\"unknown\"/></address></source><rsr type=\"success_failure\"/><ud" +
                "type=\"text\">Hello World</ud></sms></message>";
            httpconn.getOutputStream().write(reqstring.getBytes(), 0, reqstring.length());

            byte b[]=new byte[httpconn.getInputStream().available()];
            //System.out.println(httpconn.getContentType());
            httpconn.getInputStream().read(b);
            System.out.println(Thread.currentThread().getName()+new String(" Request"+rst.getString(1)));
            //System.out.println(new String(b));
            httpconn.disconnect();
            Thread.sleep(100);

            }
         catch(Exception e){
            e.printStackTrace();
        }

       }
            System.out.println(Thread.currentThread().getName()+"  "+new java.util.Date());
       }
       catch(Exception e){
           e.printStackTrace();
       }

    }

    public static void main(String[] args) throws Exception{
       System.out.println(new java.util.Date());
       System.out.println("Memory-before "+Runtime.getRuntime().freeMemory());
        Thread t1=new Main("T1-");
        Thread t2=new Main("T2-");
        Thread t3=new Main("T3-");
        Thread t4=new Main("T4-");
        t1.start();
        t2.start();
        t3.start();
        t4.start();

        System.out.println("Memory-after "+Runtime.getRuntime().freeMemory());


    }

}

我需要在所有线程执行后关闭连接。有没有什么好的主意可以这样做。请帮助我完成这项工作。

最佳答案

您可以使用Runtime.addShutdownHook()注册应在 JVM 关闭之前运行的代码。

关于java:所有线程终止后关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2506604/

相关文章:

c# - 如何导出 C# 方法?

c - 使用静态函数的正确方法是什么?

Java - 使用分隔符不删除特殊字符

java - Mockito:如何部分使用 @InjectMocks-Annotation 进行 MockMvc 测试?

java - 为什么我的 Java while 循环首先进行两次传递?

java - 返回外部方法错误

c++从类外部调用方法

java - 为密码过期的用户重定向至更改密码页面

在 C 中将函数调用到另一个函数反之亦然

java - 从类的方法代码中调用方法或在类的实例上调用方法有区别吗?