开发者

How do I fix a Thread Leak in a JSF application?

开发者 https://www.devze.com 2023-04-09 19:35 出处:网络
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 t

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.


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");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号