Question

I was wondering... Let's say that I have two stateless beans in ejb 3.1:

  1. @Stateless Class1

    @EJB MyUniqueInstanceBean uniqueBean1;

2.

@Stateless
Class2

@EJB MyUniqueInstanceBean uniqueBean2;

Are uniqueBean1 and uniqueBean2 guaranteed to be unique instances of MyUniqueInstanceBean?

Was it helpful?

Solution

If MyUniqueInstanceBean is Stateless it is not in your hands are calls to uniquebean1 and uniquebean2 actually calls to same instance. In EJB 3.1 specification this is told with following words:

Because all instances of a stateless session bean are equivalent, the container can choose to delegate a client-invoked method to any available instance. This means, for example, that the container may delegate the requests from the same client within the same transaction to different instances, and that the container may interleave requests from multiple transactions to the same instance.

If MyUniqueInstanceBean is Stateful, it is guaranteed that uniquebean1 and uniquebean2 do not refer to same instance. Again from specification:

A session bean instance’s life starts when a client obtains a reference to a stateful session bean instance through dependency injection or JNDI lookup, or when the client invokes a create method on the session bean’s home interface. This causes the container to invoke newInstance on the session bean class to create a new session bean instance.

If you are using Singleton, then both refer to same instance, because there is only one instance:

A Singleton session bean is a session bean component that is instantiated once per application. In cases where the container is distributed over many virtual machines, each application will have one bean instance of the Singleton for each JVM.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top