If there is an exception during the run-time of a thread,
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
}
}
}
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();
}
}
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:
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.Callable<T>
is a task implementation. Perhaps pretty similar to what you may be doing not with Runnable
objects.Future<T>
holds a promise for a task result.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With