1

I have an ApplicationScoped bean that fires up a separate Thread to do some background work. The Thread has a method for cleanly terminating it called terminate(). If not terminated via that method it runs in an infinite loop, and sleeps for a while if it finds it has nothing to do.

The thing is I am in development mode (Netbeans -> Maven) and each time I recompile the application, the Maven plug-in un-deploys and redeploys the application (most conveniently I must say) but the background Thread from the last deployment hangs around. It eventually terminates with an Exception because it wakes up from its sleep and tries to access a JPA EntityManager that isn't there anymore.

I would prefer to automatically call the terminate() method when the application is stopped. Is there some way to implement a listener that will do that at the JSF 2.0 specification level? If not, how about at the Servlet level?

This is using GlassFish 3.1.1.

AlanObject
  • 9,613
  • 19
  • 86
  • 142
  • 1
    Related: http://stackoverflow.com/questions/7499534/applicationscope-bean-that-uses-a-timertask-sheduler-good-or-bad – BalusC Oct 02 '11 at 20:11

1 Answers1

2

Add a @PreDestroy method to you bean which will run when your application is undeployed or stopped and it can stop the background thread, like this:

import javax.annotation.PreDestroy;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

@ApplicationScoped
@ManagedBean
public class AppBean {

    public AppBean() {
        System.out.println("new AppBean()");
    }

    @PreDestroy
    public void preDestory() {
        // call thread.terminate() here
        System.out.println("preDestory");
    }
}
palacsint
  • 28,416
  • 10
  • 82
  • 109
  • My application scoped bean is managed by CDI -- is it expected to process the **PreDestroy** annotation? – AlanObject Oct 02 '11 at 23:18
  • Yes, I think so. "The Java EE `@PostConstruct` and `@PreDestroy` callbacks are also supported for all managed beans.", from: http://docs.jboss.org/weld/reference/1.1.0.Final/en-US/html_single/#d0e4657 – palacsint Oct 02 '11 at 23:25