Posts tagged java
Java Gotcha: Executing code via Timer vs ScheduledExecutorService
A customer called to report that he cannot read values of two of his devices from the server. In fact, he was not able to read any values of any devices, but since he is served with the most up to date cache results for the other devices, he was not aware of that part of the problem. I connected to the server via remote debugging of Java, which kicks ass by the way, only to find out that the Timer is not executing my code which update the values of the devices currently being watched. It was weird, because the server has been running for weeks and it just stop functioning. It turned out that if an exception occurs in the code Timer is calling, Timer stops executing the code all together in the future. Which, in practice, means that one of your threads is not functioning anymore. Then I learned about ScheduledExecutorService, it is specifically designed to run code. It handles exceptions much more gracefully. So, long story short, use ScheduledExecutorService instead of Timer when you want to execute code. The good thing is, it is quite easy to port your code to use ScheduledExecutorService.