2

I have a process that one of its background threads (Thread-A) does a task. If the process hangs/crashes, I want to make sure that the background thread crashes/stops as well (ok for me).

What I mean is I don't want to be in a situation where some of the threads are crashed and so the process essentially is non-functional and that background thread (Thread-A) keeps going.

I need to somehow make that thread understand the problem.
Is there a pattern for this? Some kind of health check may be? Still though how can I be sure I don't get the same problem with the health check thread.

Perhaps I am confused on this. Could you please help me out?

midhunhk
  • 5,560
  • 7
  • 52
  • 83
Jim
  • 18,826
  • 34
  • 135
  • 254

2 Answers2

1

You need to look at the ExecutorService in java.util.concurrent, you can then ask the service to terminate when the main thread exits using ExecutorService.shutdown() as long as your background thread is periodic so can be stopped.

Otherwise you need to use an AtomicBoolean to signal between threads and tell the background thread to exit when the boolean is false.

Finally, to detect crashes in the first thread use an UncaughtExceptionHandler with a callback that signals the background thread to exit.

Of course this can all be avoided by using daemon threads but that would not allow the background thread to clean up after itself if it gets unexpectedly killed.

Community
  • 1
  • 1
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • It is not about signaling among threads but healthchecks and understanding that there is a problem. – Jim Feb 19 '13 at 10:50
1
public class HealthChecker
{
    public final long THRESHOLD = 10000L; // 10 seconds

    private final Map <Thread, Long> lastFineReports =
        new ConcurrentHashMap <Thread, Long> ();

    /**
     * Each thread should call this method periodically.
     */
    public void iAmFine ()
    {
        lastFineReports.put (
            Thread.currentThread (), 
            Long.valueOf (System.currentTimeMillis ()));
    }

    /**
     * Used by whatchdog to know whether everything is OK.
     */
    public boolean isEverythingOK ()
    {
        Long [] timestamps = 
            lastFineReports.
                values ().
                    toArray (new Long [lastFineReports.size ()]);

        long now = System.currentTimeMillis ();
        for (Long t: timestamps)
            if (now - t.longValue () > THRESHOLD)
                return false;

        return true;
    }
}
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40