0

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?

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

sure =) but I want to monitor every exception and error and send an e-mail if something goes wrong with my tool =)
@Xelluloid: You could certainly add a sort of "heartbeat" in the timer thread, and then add a new thread to check that heartbeat every so often. It does just push the same problem one level higher though :)
0

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.

1 Comment

but it is not an exception that is thrown but an Error :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.