如果发生异常,Java Threads是否需要清理

sur*_*a2k 5 java multithreading garbage-collection

如果在线程的运行时期间存在异常,

  1. 我需要清理还是其他什么?
  2. 如果我有数百个线程在运行,我可以使用垃圾收集器来清理我的内存吗?

class MyThread extends Thread {

    public void run() {
        try {
            MyDAO dao = new MyDAO();
            List<Results> res = dao.findResults(...);
            ....
        } catch(Exception e) {
            //Do I need any clean up here
        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 5

run方法完成时,无论是正常还是由于异常,它创建的所有对象都可以自由地进行,无需进行特定的清理.

您只需要清理需要关闭的资源(数据库连接,文件流等).这种清理通常finally在你的后续条款中完成catch.

public void run(){
    Statement statement;
    try{
        MyDAO dao = new MyDAO(); // doesn't need closing
        List<Results> res = dao.findResults(...);
        statement = getStatement(); // must be closed
        ....
    } catch (Exception e){
        // handle the error
    } finally {
        if (statement!=null) statement.close();
    }
}
Run Code Online (Sandbox Code Playgroud)