4

Does anyone know whether the initialization of instance fields within a method annotated with PostConstruct is considered to be thread safe? I am not quite sure if i have to make my fields of my ApplicationScoped bean volatile or not so other threads can really see the values...

Thanks for any hints or answers!

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58

1 Answers1

2

I don't have a direct reference to the spec that absolutely guarantees this, but @PostConstruct should be thread safe.

The CDI runtime is fully in charge of creating beans and will only create one instance for a given scope. @PostConstruct runs before the bean is accessible in such a scope or via injection.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
  • Thanks man, would be even better if you could tell me for sure, since from a JMM perspective i think i would have to make them volatile, if there were no memory barriers. – Christian Beikov Dec 16 '12 at 11:15
  • You would think, but likely your other threads won't even get a reference to the instance before CDI has initialized the bean. In case of concurrent requests for a bean, I'm pretty sure all threads are stuck on the hypothetical `beanManager.getBean(...)` call. – Arjan Tijms Dec 19 '12 at 14:06
  • Thanks, that's of course the only behavior that makes sense, but I wanted to know it for sure without having to read the spec. ;) – Christian Beikov Dec 20 '12 at 04:04