CDI PostConstruct和volatile字段 [英] CDI PostConstruct and volatile fields

查看:132
本文介绍了CDI PostConstruct和volatile字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们想要有条件地初始化某些bean的字段时使用post构造方法,我们是否需要关心该字段的波动性,因为它是一个多线程环境?

Using a post construct approach when we want to conditionally initialise some of the bean's fields, do we need to care about volatility of the field, since it is a multithread environment?

说,我们有这样的事情:

Say, we have something like this:

@ApplicationScoped
public class FooService {

    private final ConfigurationService configurationService;

    private FooBean fooBean;

    @Inject
    FooService(ConfigurationService configurationService) {
         this.configurationService = configurationService;
    }

    void init(@Observes @Initialized(ApplicationScoped.class) Object ignored) {
        if (configurationService.isFooBeanInitialisationEnabled()) {
             fooBean = initialiseFooBean(configurationService); // some initialisation
        }
    }

    void cleanup(@Observes @Destroyed(ApplicationScoped.class) Object ignored) {
       if (fooBean != null) {
           fooBean.cleanup();
       }
    }
}

所以应该 fooBean 被包装成,比方说, AtomicReference 或者是 volatile 或者它将是一个多余的额外保护?

So should the fooBean be wrapped into, let's say, the AtomicReference or be a volatile or it would be a redundant extra protection?

PS 在这种特殊情况下,它可以重新表述为:后构造和后破坏事件执行是否由同一个线程?但是我希望得到一个更一般的案例的答案。

P.S. In this particular case it can be reformulated as: are post construct and post destroy events performed by the same thread or not? However I would like to have an answer for a more general case.

推荐答案

我想说这取决于哪个线程实际上是在启动和摧毁背景。
如果您使用常规事件,它们是同步的(CDI 2.0中添加了异步事件,其中 ObservesAsync ,请参阅
Java EE 8:使用ManagedExecutorService发送异步CDI 2.0事件)因此它们在同一个线程中被调用调用者。

I would say it depends which thread is actually initiating and destroying the contexts. If you use regular events, they are synchronous (asynchronous events have been added in CDI 2.0 with ObservesAsync, see Java EE 8: Sending asynchronous CDI 2.0 events with ManagedExecutorService ) so they are called in the same thread as the caller.

一般情况下,我不认为使用相同的线程(在应用程序服务器或独立应用程序中)所以我建议使用 volatile 以确保看到正确的值(基本上是在destroy线程上构建的值)。但是,以并发方式启动和销毁您的应用程序并不是一个用例......

In general, I don't think the same thread is used (in application servers or standalone applications) so I would recommend using volatile to ensure the right value is seen (basically the value constructed seen on destroy thread). However, it is not a use case happening so much to initiate and destroy your application in a concurrent way...

这篇关于CDI PostConstruct和volatile字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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