thread catching and stopping an OutOfMemoryError

  • Thread starter Ivan Villanueva
  • Start date
I

Ivan Villanueva

Hello,
I have a Thread object which sometimes throws an OutOfMemoryError.
Is it possible to stop (destroy) that thread without terminating the main
process ?

I have thought about something like that:

searchThread.setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {

}
}) ;

Or, is there a trick to know when a thread is going to throw one ?

Iván Villanueva.
 
T

Tris Orendorff

Ivan Villanueva said:
Hello,
I have a Thread object which sometimes throws an OutOfMemoryError.
Is it possible to stop (destroy) that thread without terminating the main
process ?

I have thought about something like that:

searchThread.setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {

}
}) ;

How about a try/catch inside your run method? Something like:

public void run() {
try {
while (...) {
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
// leaving the run method signifies the end of this thread
}

// sorry about the typos. I am nowhere near a java compiler.

--

Sincerely,

Tris Orendorff
[Two antennae meet on a roof, fall in love and get married. The ceremony wasn't much, but the reception
was excellent.]
 
A

Antti S. Brax

I have a Thread object which sometimes throws an OutOfMemoryError.
Is it possible to stop (destroy) that thread without terminating the main
process ?

If an OutOfMemoryError (or any other unchecked exception) is
thrown and not handled, the thread that executed the method
in which the exception was thrown will be terminated.

As long as your program has one or more non-daemon threads
running, your program will not be terminated by an unhandled
exception (of course, if the exception is thrown in your last
non-daemon thread, then the program will be terminated). The
other threads will keep running.
Or, is there a trick to know when a thread is going to throw one ?

No. It is obvious that an OutOfMemoryError is more likely to
occur when a large amount of memory is reserved. But it is
still possible that the large allocation succeeds and the next
allocation for 4 bytes (possibly in some other thread) will
fail.

If you want to prepare for unchecked exceptions, I suggest that
you start by reading this:
http://www.octopull.demon.co.uk/java/MoreExceptionalJava.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top