Do Java Threads need a cleanup if exceptions occurred

garbage-collection, java, multithreading

Solution

When the `run` methods finishes, be it normally or due to an exception, all the objects it creates are free to be garbaged, no need for a specific cleanup.

You only need a cleanup for the resources that need closing (DB connections, file streams, etc.). This cleanup is normally done in a `finally` clause after your `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();
    }
}

Problem

If there is an exception during the run-time of a thread, - Do I need to clean up or something else? - If I have hundreds of threads running, can I use garbage collector to clean up my memory ? ``` 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 } } } ```

Original source