Search code examples
jakarta-eeejbjavabeanscdivolatile

Java EE beans and volatile keyword


Servlet, EJB and CDI parts of Java EE specification describe bean management (injection and etc..). But also specification does not describe (explicitly or implicitly) concurrency properties of the bean container. If I've used WildFly or GlassFish, then the Java EE application server can access to bean object more from one thread.

So the question is, do have I to use volatile keyword with all bean fields, which theoretically can be accessed from more than one thread (i.e. for almost all beans, and, at least, for all fields annotated with @Inject)?


Solution

  • The technical answer depends on kind of bean and kind of property, but normally you don't need to worry about this at all.

    In case of EJBs, the container already enforces some default concurrency control which you can control by @Lock and @ConcurrencyManagement annotations. See also a.o. EJB @Asynchronous to retrieve real time inserted row in JSF seems to be thread locked.

    In case of JPA entities, any need for concurrency control suggests a major design/fundamental problem. Concurrency control should only be enforced in the controller, not the model nor the view. JPA entities themselves do in no way represent the "controller". In other words, a volatile field in a JPA entity doesn't make any sense, while a volatile field in a managed bean referring the JPA entity itself might make sense.

    In case of managed beans (JSF/CDI), usually if you come to a point you worry about concurrency on some managed bean, it's much more likely that the scope of the bean is wrong and needs to be narrowed down. E.g. using @ViewScoped or @ConversationScoped instead of @SessionScoped or even @ApplicationScoped. See also a.o. How to choose the right bean scope?

    In case of application scoped beans ("singletons" in widest sense), it may make sense, but only if there doesn't already exist a concurrent/atomic wrapper class for the field of interest, such as ConcurrentMap, AtomicBoolean, etcetera. See also a.o. Concurrency of @ApplicationScoped JSF managed beans.