Consider switching to a system where you submit jobs to an Executor from the thread pulling stuff off of the process:
public class MyThread extends Thread {
private final InputStream processStream;
private final Executor executor = Executors.newSingleThreadExecutor();
public MyThread(InputStream processStream) {
this.processStream = processStream;
}
@Override
public void run() {
while ([processStream has stuff]) {
final Object obj = // Get your object from the stream
executor.execute(new Runnable() {
@Override
public void run() {
// Do database stuff with obj
}
});
}
}
private static Object getSomethingFromStream(InputStream stream) {
// return something off the stream
}
}
If an exception is thrown by your Runnable, it will be logged, but it won't be stopped, and it will just continue to the next job in the queue. Also note that this is using a single-threaded executor, so everything submitted will be executed one at a time, and in the order they're submitted. If you want concurrent execution, use Executors.newFixedThreadPool(int) or Executors.newCachedThreadPool(). Note that this answers how to keep your thread alive. If you want to resubmit a runnable for re-execution if the job fails, change its run method to:
@Override
public void run() {
try {
// Do database stuff with obj
} catch (PeristenceException ex) {
// Try again
executor.execute(this);
}
}
You can add logic to this to tailor when it will try again on an exception.