Multi-threading in EJB's
Asked Answered
I

1

5

I am learning about EJB's, so far I have read that multi-threading is not allowed in EJB'S, because it is the container who should care about thread-safety and let the developer only focus in the business logic, so basically that means that EJB ensures that only one thread has access at the same time to a method in a Session bean.

What happens then when we have many users accessing to the same method in a EJB? Is the container serializing the acceses, or is creating different instances of the bean, one per thread?

Could someone explain me what is the policy about that? Also I am a bit confused, why if multithreading is not allowed, so we cannot create our own threads, why we have this @Asynchronous annotation?

Ishmaelite answered 3/5, 2015 at 11:51 Comment(0)
L
8

Yes, it creates several instances, and pools them. See the official Oracle documentation:

Because a stateless session bean is never passivated, its lifecycle has only two stages: nonexistent and ready for the invocation of business methods. Figure 22-4 illustrates the stages of a stateless session bean.

The EJB container typically creates and maintains a pool of stateless session beans, beginning the stateless session bean’s lifecycle. The container performs any dependency injection and then invokes the method annotated @PostConstruct, if it exists. The bean is now ready to have its business methods invoked by a client.

At the end of the lifecycle, the EJB container calls the method annotated @PreDestroy, if it exists. The bean’s instance is then ready for garbage collection.

Littles answered 3/5, 2015 at 11:55 Comment(4)
Quick question, is the synchronization done at the method level or class level? If I well understood, if two users try to access to the same method in the same EJB instance, the EJB container will create another instance of the EJB to execute the same method in different instances, what happen if the method is not the same? Another instance will be created anyway?Ishmaelite
It's done at the instance level. The container will not allow two threads to concurrently inoke a given bean instyance, whatever the method is. And it typically doesn't create a new instance. It gets one from the pool.Littles
Just a las question, do you know what is the initial size of this pool of ejb's? I mean initially the EJB container creates a pool of two, three...., how many instances? And I guess once all the instances of the pool are being used, it will create new ones if it is required, right?Ishmaelite
That depends on the application server. You'll have to dig into its documentation.Littles

© 2022 - 2024 — McMap. All rights reserved.