EJB and Synchronization

Only one thread at a time will be accessing your beans. It is up to the application server to manage this. So you should not be using synchronized from within your beans. This is why a non-threadsafe like EntityManager can be an instance value and not have synchronization issues.


Stateless beans: Every thread/request will get different instance of EJB from pool. SLB should not hold any user session data, any state. The same code may be executed in parallel. One instance is accessed by one thread at a time.

Statefull beans are synchronized for user session. Every user will get own session scoped instance. Second thread/request will wait until the first thread finishes. Statefull EJB can hold user specific data. One user cannot execute same code in parallel. Different users may execute same code in parallel.

If accessing a resource that does not allow parallel access use Singleton EJB. As name implies there is only one instance. By default EJB Singleton can be accessed only by one thread (Container Managed Concurrency and @Lock(WRITE)).