How is singleton javax.ejb.Singleton in a clustered environment?

I need to maintain a simple counter, unique in the application, for all users and all nodes in a cluster environment. I was thinking about using the javax.ejb.Singleton annotation bean singleton session like this:

package foo; import javax.ejb.Singleton; @Singleton public class Bean { private int counter; [...] } 

It looks simple, but I could not find the answer if it works as desired in a clustered environment. Each node in the cluster has its own instance or not?

Of course, I could save the bean in the database, but in reality it is only a counter, and that would be superfluous. In addition, I want the counter to be reset when the application crashes or is restarted, so saving it will create more problems than it solves.

+5
source share
3 answers

Will each cluster node have its own instance or not?

Yes, each node cluster will have a different instance of Singleton. Therefore, @Singleton annotation is not a solution to your problem.

Note that the Java EE specification does not define any cluster behavior. You need to find a specific solution to solve this requirement. For an example, see Link.

+9
source

You can use hazelcast . This is a distributed keystore in memory. It looks like it will be perfect. It also implements JSR-107, which is a JCache specification.

+2
source

Ha singleton is an approach. As an advance, there are some restrictions. If you read, you will have an @stateless bean that will access the service using the getValue () method. The get value calls the singleton bean methods and gives you the value ... everything until it is.

But if you need to work with a bean, the strategy should return an instance of SingletonBean through the get value, but .. you will have more instances of this singleton bean .... and there is a problem.

-2
source

All Articles