Sebastian Müller
Sebastian Müller

Reputation: 5589

Exception when losing a thread

I start two threads with a Timer and TimerTasks

Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                public void run() {
                    doSomething();
                }
            };
            Calendar start = Calendar.getInstance();
            timer.scheduleAtFixedRate(task, start.getTime(),
                    1000 * 60 * 60);

Now sometimes the second thread stops. Is there a possibility to observe the thread perhaps for sending a mail when this thread stops, maybe by a third thread that looks for the second thread?

Upvotes: 0

Views: 147

Answers (2)

brianegge
brianegge

Reputation: 29892

I'd suggest adding a Thread#setDefaultUncaughtExceptionHandler to your program. You can have this log/email/etc.. While having a catch(Throwable) is better design, having an uncaught exception handler can handle any cases you miss.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503429

You need to keep the reference to your Timer alive - if the Timer is garbage collected, the thread will stop. From the docs:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the timer's cancel method.

That may not be the problem, but it's the most likely cause. I assume if you can keep the thread alive, you don't need anything checking it?

Upvotes: 2

Related Questions