I have a singleton that needs to start a scheduled execution. This is the code:
public enum Service{
INSTANCE;
private Service() {
startAutomaticUpdate();
}
private void startAutomaticUpdate() {
try {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new AutomaticUpdate(), 0, 15, TimeUnit.MINUTES);
} catch (Exception e) {
LOG.error(e.getMessage() + "Automatic update not working: ");
}
}
//Makes a call to a webservice that updates a static variable.
private void getTemplateNames(){...}
private class AutomaticUpdate implements Runnable {
public AutomaticUpdate() {
}
@Override
public void run(){
try{
getTemplateNames();
}catch(Exception e){
LOG.error("Error in automatic update: "+e.getMessage());
}
}
}
I am not sure when or if I should call the shutdown method of the executor. I'm using JEE5, so I'm not sure if simply undeploying the app will automatically execute the shutdown, or if I am messing up big time and creating a ridiculous amount of threads and not killing them.
-EDIT-
I'll add a bit more info, just in case.
The whole app is a RESTful web app using Jersey as a ServletContainer.
You said JEE5? Why you're reeinventing the wheel?Just create a EJB with
@Schedule
and@Startup
No you don't mean JEE5 complaint server. :(
Go for the implementation with a ServletContextListener. I wrote some answer like that here, It's the same idea, it does applies here.