在JSF管理的bean中启动新线程是否安全? [英] Is it safe to start a new thread in a JSF managed bean?

查看:216
本文介绍了在JSF管理的bean中启动新线程是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到在会话范围的JSF托管bean中产生线程是否安全的确切答案。线程需要调用无状态EJB实例上的方法(这是依赖注入到受管Bean)。

I could not find a definitive answer to whether it is safe to spawn threads within session-scoped JSF managed beans. The thread needs to call methods on the stateless EJB instance (that was dependency-injected to the managed bean).

背景是我们有一个需要很长时间的报告时间生成。这导致HTTP请求由于服务器设置超时而无法更改。所以这个想法是开始一个新的线程,让它生成报告并临时存储它。在此期间,JSF页面显示一个进度条,轮询托管bean,直到生成完成,然后再次下载存储的报告。这似乎是有效的,但我想确定我在做什么不是黑客。

The background is that we have a report that takes a long time to generate. This caused the HTTP request to time-out due to server settings we can't change. So the idea is to start a new thread and let it generate the report and to temporarily store it. In the meantime the JSF page shows a progress bar, polls the managed bean till the generation is complete and then makes a second request to download the stored report. This seems to work, but I would like to be sure what I'm doing is not a hack.

推荐答案

简介< h2>

在会话范围内管理的bean中生成线程不一定是黑客,只要它执行所需的任务即可。但是,自己产生的线程需要非常小心。代码不应该以单个用户的方式写出,例如每次会话产生无限量的线程,和/或线程在会话被破坏之后继续运行。它将会迟早炸毁您的应用程序。

Introduction

Spawning threads from within a session scoped managed bean is not necessarily a hack as long as it does the job you want. But spawning threads at its own needs to be done with extreme care. The code should not be written that way that a single user can for example spawn an unlimited amount of threads per session and/or that the threads continue running even after the session get destroyed. It would blow up your application sooner or later.

代码需要以这种方式写入,以确保用户可以永远不会产生多个后台线程每个会话,线程被保证在会话被破坏时中断。对于会话中的多个任务,您需要对任务进行排队。

The code needs to be written that way that you can ensure that an user can for example never spawn more than one background thread per session and that the thread is guaranteed to get interrupted whenever the session get destroyed. For multiple tasks within a session you need to queue the tasks.

此外,所有这些线程都应该优先由公共线程池提供服务,以便您可以在应用程序级别对所生成的线程的总数进行限制。一般Java EE应用程序服务器提供容器托管线程池,您可以通过EJB的 @Asynchronous @Schedule 。要独立于容器,您还可以使用Java 1.5的Util并发 ExecutorService ScheduledExecutorService

Also, all those threads should preferably be served by a common thread pool so that you can put a limit on the total amount of spawned threads at application level. The average Java EE application server offers a container managed thread pool which you can utilize via among others EJB's @Asynchronous and @Schedule. To be container independent, you can also use the Java 1.5's Util Concurrent ExecutorService and ScheduledExecutorService for this.

下面的示例假定Java EE 6+与EJB。

Below examples assume Java EE 6+ with EJB.

@Named
@RequestScoped // Or @ViewScoped
public class Bean {

    @EJB
    private SomeService someService;

    public void submit() {
        someService.asyncTask();
        // ... (this code will immediately continue without waiting)
    }

}





@Stateless
public class SomeService {

    @Asynchronous
    public void asyncTask() {
        // ...
    }

}



在页面加载上异步获取模型



Asynchronously fetch the model on page load

@Named
@RequestScoped // Or @ViewScoped
public class Bean {

    private Future<List<Entity>> asyncEntities;

    @EJB
    private EntityService entityService;

    @PostConstruct
    public void init() {
        asyncEntities = entityService.asyncList();
        // ... (this code will immediately continue without waiting)
    }

    public List<Entity> getEntities() {
        try {
            return asyncEntities.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new FacesException(e);
        } catch (ExecutionException e) {
            throw new FacesException(e);
        }
    }
}





@Stateless
public class EntityService {

    @PersistenceContext
    private EntityManager entityManager;

    @Asynchronous
    public Future<List<Entity>> asyncList() {
        List<Entity> entities = entityManager
            .createQuery("SELECT e FROM Entity e", Entity.class)
            .getResultList();
        return new AsyncResult<>(entities);
    }

}

如果您使用JSF实用程序库 OmniFaces ,如果您使用 @Eager

In case you're using JSF utility library OmniFaces, this could be done even faster if you annotate the managed bean with @Eager.

@Singleton
public class BackgroundJobManager {

    @Schedule(hour="0", minute="0", second="0", persistent=false)
    public void someDailyJob() {
        // ... (runs every start of day)
    }

    @Schedule(hour="*/1", minute="0", second="0", persistent=false)
    public void someHourlyJob() {
        // ... (runs every hour of day)
    }

    @Schedule(hour="*", minute="*/15", second="0", persistent=false)
    public void someQuarterlyJob() {
        // ... (runs every 15th minute of hour)
    }

    @Schedule(hour="*", minute="*", second="*/30", persistent=false)
    public void someHalfminutelyJob() {
        // ... (runs every 30th second of minute)
    }

}



在背景中持续更新应用范围模型



Continuously update application wide model in background

@Named
@RequestScoped // Or @ViewScoped
public class Bean {

    @EJB
    private SomeTop100Manager someTop100Manager;

    public List<Some> getSomeTop100() {
        return someTop100Manager.list();
    }

}





@Singleton
@ConcurrencyManagement(BEAN)
public class SomeTop100Manager {

    @PersistenceContext
    private EntityManager entityManager;

    private List<Some> top100;

    @PostConstruct
    @Schedule(hour="*", minute="*/1", second="0", persistent=false)
    public void load() {
        top100 = entityManager
            .createNamedQuery("Some.top100", Some.class)
            .getResultList();
    }

    public List<Some> list() {
        return top100;
    }

}



另请参见:



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆