We help IT Professionals succeed at work.

Multiple Java Timers...

Maarvaadi
Maarvaadi asked
on
Medium Priority
316 Views
Last Modified: 2012-05-06
I have a need for a timer in my program which will be triggered at every n hours. Now because of a known issue which may happen once in a while there will be a stack overflow in that timer thread, causing that thread to crash. This also means that my timer is now no longer there..

What is the best way to prevent this? I know the stack overflow needs to be fixed, that is being worked on, however in the meantime, all I can think is another timer keeping track of the first timer.. I have had issues in the past when I have 2 timers then one of them fails to fire very quickly (no stack overflows then).. Pointers or suggestions?
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016
Commented:
Just make sure you don't run the task in the main thread. See the following - it doesn't crash the timer:
import java.util.Timer;
import java.util.TimerTask;
 
public class TimCrash extends TimerTask {
    private int intVal;
 
    public TimCrash(int intVal) {
	this.intVal = intVal;
    }
 
    public static void main(String[] args) {
	Timer t = new Timer();
	// Pass zero to main
	t.schedule(new TimCrash(Integer.parseInt(args[0])), 0, 5000);
    }
 
    public void run() {
	// crash it
	new Thread() {
	    public void run() {
		// Deliberately crash the thread
		int i = 100 / intVal;
	    }
	}.start();
    }
}

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Yup That did it! Thanks!!
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.