Multi-threading in EJB's - java

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?

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.

Related

Why does the EJB Timer Service use Singleton as standard?

I have been studying ejb recently and I am also reading about the timer service as well, but even though I have read about Stateless, Stateful and Singleton types of Session Beans, I still have some trouble to figure out what makes the Timer Service have a multiple instance attribute.
I have seen some examples around, and even the simplest ones use the Singleton Session Bean, so, If I were to write a simple program to test it, would it be ok to use a Stateless Bean or is it recommended to use a Singleton anyway? Also, if possible, can I have a case where a Stateless would not be optimal?
Use a singleton if you want to ensure that all timeout callbacks are invoked on the same underlying bean instance. This is important if you want to maintain state in the bean instance itself, and you want to ensure that only one timeout callback can be invoked at a time (by default, the timeout callback will use the singleton's concurrency management settings, which by default is container-managed with a write lock, so only one method on the singleton can be invoked at a time).
Use a stateless if you want to allow multiple timeout callbacks to be invoked at once. The EJB container will create new bean instances if there are multiple timeout callbacks happening concurrently.
If you want to configure a non-persistent timer to begin running when the application begins running, then you can either use the #Schedule annotation on either a stateless or singleton bean, or you can use an #Singleton #Startup bean with an #PostConstruct (and if you want the stateless behavior, you can inject the stateless bean into the stateless bean and invoke a createTimer on the stateless session bean during startup).
The reasons it uses singletons are at least 2 fold:
1.
only singletons have the capabilities of start up initialization. That means, you are able to register your timer services when your application starts.
2.
if it were to use stateless beans, then a new timer service will be registered with every stateless bean setup to serve a request. A singleton guarantees that only one of a kind of your timer is registered. Imagine a contention or integrity issues, or money losses, were you to inadvertently use a timer in a stateless bean and then more than 1 is created at more or less the same time to serve requests.

spring mvc declaring all beans singleton

I have this new mvc project where all beans are default scoped(no prototype or session).
with single application context.
i want to know
by making all beans to be default scoped are we trying to achieve the whole application to be run in single thread?
if so will that make each httprequest(from multiple or same sessions) to be queued until the previous one completes?How to avoid such scenario any advice or link would be helpful.
I am relatively new to spring and java development.
Because Spring beans are typically stateless, you can safely call them from multiple threads. That's how your application works: there is only one instance of every controller, service, DAO, etc. But your servlet container (through Spring) calls these beans from multiple threads - and it's completely thread safe.
In fact in plain servlets the situation is the same - there is only instance of each servlet and it can be accessed by infinite number of threads. As long as this servlet is stateless or properly synchronized.
Do not confuse Spring with stateless session beans in ejb that are pooled and each client gets its own instance from the pool.1
1 - In fact that's a bit dumb - since the beans are stateless by the definition, there is no point in pooling them and preventing concurrent access...
Singleton means that the there will be only one instance of each bean. Generally, such beans are processing elements that carry no state. The methods called on them are passed the context which contains the inputs to work on. Hence the method calls on such singleton beans are inherently thread-safe.

Whats the difference between a EJB object and implementation bean?

In this book Enterprise JavaBeans 3.1 they talk about EJB objects and implementation objects. I am referring to what I read about stateless session beans:
Once an instance is in the Method-Ready Pool, it is ready to service
client requests. When a client invokes a business method on an EJB
object, the method calll is delegated to any available instance in the
Method-Ready Pool. While the instance is executing the request, is is
unavailable for use by other EJB objects. Once the instance has
finished, it is immediately available to any EJB object that needs it.
Stateless session instances are dedicated to an EJB object only for
the duration of a single method call.
I understand how stateless session beans work but I don't get the difference between a EJB object and stateless session instances?
I thought I made a EJB when I annotate the class with #Stateless for example?
I think it refers the EJB object as i.e. a field in your class which references to the EJB.
It's not an EJB instance - it's a proxy which gives you access to the EJB instance.
Therefore:
public class YourClass {
#EJB
private MyEJB myEjb; // This is a proxy - not a concrete EJB instance
}
During the access, i.e. myEjb.doSomething() the container looks for free EJB instance on which the call will be executed. Another time you invoke myEjb.doSomething() the container might serve you another EJB instance.
Both times, you're using the same myEjb object, while invoked a method on (probably) different EJB instances.
That's how I would understand this paragraph.
The EJB framework provides services like transactionality for your implmenetation classes and this is done by inversion of control.
When you write a session bean, you write only the business logic of the application and the EJB contatiner handles client calls and all middleware stuff. To do so it generates EJB objects augmented with the extra functionality and also containing your business logic.
When you annotate your class, you tell the EJB container to treat it as a basis for EJB objects.
What the excerpt wishes to clarify that stateless session beans do not preserve their 'state' longer than one client request. (Not as stateful beans)
I understand how stateless session beans work but I don't get the difference between a EJB object and stateless session instances?
I think your confusion is in the use of the term 'EJB Objects'
I don't think there's any special term 'EJB Objects'. Maybe you can read
While the instance is executing the request, is is unavailable for use by other EJB objects
as
While the instance is executing the request, is is unavailable for use by any other client
and this
Stateless session instances are dedicated to an EJB object only for the duration of a single method call.
as
Stateless session instances are dedicated to a client only for the duration of a single method call. A second call from the client uses an instance from the free-pool
("client" - can be a servlet, a session bean, an mdb, or a bean managed by CDI, or a POJO which does a JNDI lookup to acquire an ejb reference)

Difference between javax.ejb.SessionSynchronization and javax.transaction.Synchronization

I am working on an EJB3 application with mainly stateless session beans (SLSB). They use container managed transactions (CMT).
I want the beans to be aware of the transactions (for logging, etc). I can implement the javax.ejb.SessionSynchronization to do this. I find that I can register a javax.transaction.Synchronization in a default interceptor also to get similar callbacks.
Are there any dis/advantages to using one over the other?
Multiple SLSB of the same type can be involved in the same transaction. As soon as a method exits, the SLSB is returned to a pool for use by the next invocation, so it is not safe for an SLSB instance to be "aware" of a transaction: by the time it is notified, the bean might be in use in another transaction.
As for SFSB, I would say there is no advantage between the two approaches in theory. However, the EJB container might be using Synchronization for various internal tasks, so using SessionSynchronization would allow the EJB container to have more control over the timing of the callbacks with respect to its own operations.
I just tried to use the javax.ejb.SessionSynchronization interface with a stateless session bean and was confused not to get any calls of the three implemented methods. Then I saw this comment in the javax.ejb.SessionSynchronization JavaDoc:
Only a stateful session bean with container-managed transaction demarcation can receive session synchronization notifications. Other bean types must not implement the SessionSynchronization interface or use the session synchronization annotations.
See also this thread for some more background. So my conclusion is that making stateless session beans transaction-aware using CMT can NOT be achieved with javax.ejb.SessionSynchronization.

multi threaded servlet; single threaded ejb

In a traditional n tier web app with servlets for web layer and ejbs(2.0) for biz layer, what is the rationale behind making the servlet model multi threaded and the ejb model single threaded?
i.e there is only 1 servlet instance for all requests, but for ejbs, for each request, there is a new bean instance assigned from the bean pool.
There is indeed only one instance for a specific Servlet since they are supposed to be stateless. In practice this isn't always the case, but so be it.
There are however multiple instances of Stateless session beans (SLSB), and those are pooled.
By their very definition, stateless session beans are stateless, so on the surface this seems like a paradox. The things is that while stateless session beans are stateless with respect to individual calls being made to them, they in fact very often have state.
This state is in the form of references to other resources. The JPA entity manager, which is not thread-safe, is a prime example here. During a single call to a stateless session bean, the caller must have exclusive access to this resource. When the call returns, the next caller can have exclusive access, etc.
If a single instance was used, then either all callers would have to wait on each other (which is of course killing for performance), or they would have the access this single instance concurrently. In the latter case, the bean implementor has to do manual locking of the non thread-safe resources like the entity manager which is often brittle, error-prone and in the end still causes callers to wait on each other.
So, in order to improve performance and still have the safety guarantee, multiple instances are being used.
Those instances are then being pooled and re-used instead of created fresh for each request, because finding, initializing and injecting all required dependencies of the bean can potentially be time consuming.
All of this thus automatically also means that if you inject an entity manager or other non thread-safe resource into a Servlet (which is allowed), you may run into problems. This is a small loop-hole in the Java EE architecture, which is of course easily worked around by simply making use of stateless session beans.
I think that typically servlets present thin facade to the heavy logic implemented in EJBs. Servlets should be stateless and therefore there is no reason to create more than one instance of the same servlet.
If you are using stateless beans only I think that there is no reason to have more than one instance too. But statefull EJBs have state and therefore you need instance per simultaneous request.
I hope I did not say bullshit.

Categories