1

I have been reading lately about safe publication of Java objects (e.g. here: http://shipilev.net/blog/2014/safe-public-construction/).

Until now I was trusting EJB container without questions when relying on container managed concurrency.

Now I'm wondering 1) how an EJB container can make sure that the EJB itself is published safely? 2) how an EJB container can make sure that objects created by its EJBs are published safely (e.g. EJB instance vars)?

E.g. stateless session bean can be accessed by different threads over time (I'm not necesseraly saying simultaneously), so unsafe publication is a potential issue.

For 1), I roughly see possibilities, e.g. by wrapping the EJB and using some volatile accesses to garantuee total order.

For 2), I don't see how EJB container can enforce it. Maybe it is forbidden by the EJB 3.1 spec to keep instance variables in the EJB if it can be accessed by different threads? Maybe the statement "don't worry about concurrency in container managed EJB" is not true, and I should use safe publication patterns (including volatile and/or final keywords) in the class definitions of the classes used in my EJB instance vars?

I'm surpirsed I missed this fundamental problemacy for that many years as a Java developer.

Regards, Lars

Lars
  • 11
  • 3

1 Answers1

0

If an EJB container is reusing instances, it must store them in a thread-safe object pool, which must use some synchronization (synchronized, compare-and-swap, etc.), which will ensure that everything written by the first thread will "happen-before" everything that happens on the second thread. EJB developers do not need to worry about synchronization (unless they're using singleton session beans with bean-managed concurrency or the EJB is going outside the scope of the EJB spec by storing data in static variables).

Brett Kail
  • 33,593
  • 2
  • 85
  • 90