Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Java Threads need a cleanup if exceptions occurred

If there is an exception during the run-time of a thread,

  1. Do I need to clean up or something else?
  2. 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
        }
    }
 }
like image 731
sura2k Avatar asked May 03 '13 12:05

sura2k


3 Answers

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();
    }
}
like image 67
Denys Séguret Avatar answered Oct 27 '22 13:10

Denys Séguret


You do not need particular cleanup, unless you have open system resources likes files. As soon as threads terminate, no matter whether normal or exceptional, they're are cleaned by the OS or VM (thread stack, ...).

The Thread objects themselves are reclaimed by the plain Java GC. Generally GC will perform a collection when you're running low on memory. However, it's not deterministic.

To improve memory efficiency in general, you might consider refactoring your threads into tasks and a thread pool, which shaves off around one megabyte (rough figure!) per thread:

  • An implementation of ExecutorService runs tasks on threads. If you're mainly doing CPU work rather than I/O it's generally sensible to have as many threads as cores rather than hundreds of threads. There are existing implementations, but you can also implement your own executor service.
  • A Callable<T> is a task implementation. Perhaps pretty similar to what you may be doing not with Runnable objects.
  • A Future<T> holds a promise for a task result.
like image 26
Matthias Meid Avatar answered Oct 27 '22 14:10

Matthias Meid


Objects are automatically eligible garbage collected when they have no more references, so as long as nothing from your threads is being referenced from other Objects, then you should be okay.

It's important to note that Java's garbage collection (using System.gc()) won't guarantee the garbage collection to happen.

like image 2
austin Avatar answered Oct 27 '22 12:10

austin