Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to maintain a simple counter that is unique within the application, for all users and all nodes in a clustered environment. I thought about using the singleton session bean annotation javax.ejb.Singleton like so:

package foo;

import javax.ejb.Singleton;

@Singleton
public class Bean {
    private int counter;
    [...]
}

This looks simple, but I could not find an answer if this works as desired in a clustered environment. Would every node of the cluster have it's own instance or not?

Of course I could persist the bean in a database, but it's really only a counter and doing so would be overkill. Also, I want the counter to reset on application crash or restart, so persisting it would create more problems than it solves.

like image 871
Christian Schlichtherle Avatar asked Apr 07 '15 16:04

Christian Schlichtherle


People also ask

What is singleton EJB?

ejb. Singleton annotation is used to specify that the enterprise bean implementation class is a singleton session bean: @Singleton public class SingletonBean { ... }

How does singleton work in distributed environment?

We use Singleton to cache some custom information from Database. Its mostly read-only but gets refreshed when some particular event occurs. Now our application needs to be deployed in a Clustered environment. By definition, each JVM will have its own Singleton instance.

What is singleton cluster?

A cluster-singleton is a service that is deployed across multiple cluster nodes, which is never active in more than one node concurrently.


2 Answers

Would every node of the cluster have it's own instance or not?

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

Take in mind that Java EE specification doesn't define any kind of cluster behavior. You need to search for specific vendor solution to achieve this kind of requirement. Just as an example see this link.

like image 74
Gabriel Aramburu Avatar answered Oct 19 '22 17:10

Gabriel Aramburu


You could use hazelcast . It's a distributed in-memory key-value store. Seems like it would be a perfect fit. It also implements JSR-107 which is the JCache spec.

like image 26
mamboking Avatar answered Oct 19 '22 16:10

mamboking