I have heard about @Singletone annotation in EJB 3.x specification. However through my past experience I know that it is actually not a singletone in a multi-node environment (Correct me if I am wrong).
Could you please, explain that annotation in a detail and tell if there is really a way to enforce singletone pattern to some entity across multiple nodes domain. May be at least to multiple classloaders jvm (J2EE compliant application server)?
I migh be wrong, but I would assume that one would need some kind of native level development to achieve that.
Yes, it's true - the @Singleton annotation annotates a special type of SLSB for which only one instance in whole application can exist (1 instance per JVM).
It's correct that in the multi-noded environment this is no longer a "singleton" in the context of the whole environment. The situation is the same as with ServletContext in Servlets (1 context per JVM).
However, I am -- just like you -- quite interested how you can (if it's possible!) achieve the multi-node environment singleton...
Each Singleton can be annotated as @Startup which will make the instance available just after the container initialization. Moreover, each managed bean can have @PostConstruct method which will be invoked when particular bean instance is initialized and all dependency injection is done.
Perhaps this is the place in which you should take care of 'synchronizing' all Singleton instances in the environment in order to hold the same state?
Small correction. A @Singleton is not really a SLSB (stateless session bean), since a @Singleton is allowed to maintain state across business method calls. i.e. You can change the state of a singleton during a business method invocation and expect that state to be available in the subsequent business method invocation (unlike SLSB).
You're right - I just wanted to express that it works somewhat similar to the situation where you enforce the container to hold only and exactly one instance of a SLSB. For what I remember, the SLSB can also hold some state, but you cannot be sure if consecutive calls will return the same value you left there as you have no idea if it's the same instance you previously invoked. In @Singleton you're just sure that it's the same instance over and over again.
Pedro Kowalski wrote:
Does the CDI's @ApplicationScoped solve the problem of multi-node (multi-JVM) environment and preserves only one instance for all JVM's?
To my best knowledge it does, because all references to @ApplicationScoped are proxied, and therefore are correctly resolved by the CDI container, regardless on how many nodes the application is distributed.