Creation and Use of Singleton under Jboss5.1 with EJB3.0 Annotations.

Hi,

I had a case where I needed to use the same variable shared between couple of stateless beans.

In a stand alone java program we would set it as Static.

But since we are under Server application container(this case Jboss) we know that the container has pool of EJB’S sessions which is being created for us.

A static variable in such environment might get duplicated(specially in Cluster mode) and therefor wont serve out target.

So for this purpose we will create Singleton class which will hold our “static” variables.
that Singleton class will have only one instance throughout our application deployment.

Some code:

First we create the Singleton interface:

import javax.ejb.Local;

@Local
public interface SingletonBeanLocal
{
	 int getAttribute();
	 void setAttribute(int x);

}

Now we will create Singleton Management class:

* Note: We must implement Management class in order to achieve Singelton MBean.

import org.jboss.ejb3.annotation.Management;

@Management
public interface SingletonBeanManager
{
	 int getAttribute();
	 void setAttribute(int x);
}

Now we are going to implement these Interfaces:

import javax.ejb.Local;
import org.jboss.ejb3.annotation.Service;

@Service(objectName = "jboss:custom=Singleton")
@Local(
{ SingletonBeanLocal.class })
public class SingletonBean implements SingletonBeanManager, SingletonBeanLocal
{
	private int xyz = 0;

	@Override
	public int getAttribute()
	{
		return xyz;
	}

	@Override
	public void setAttribute(int x)
	{
		xyz++;
	}
}

The @Service and @Management combined together will install a Singleton MBean which can also be controlled via JMX console.

Since this Mbean is registered as service it will be the only one installed and it’s “local” variables” could be use as “Static” in our terms.

Now all we need is to Lookup/Inject to the Singleton Mbean and retrieve/set our variables.

Hope you got it,
Idan.
[ad]

Related Articles:

(2593)

Be Sociable, Share!

One thought on “Creation and Use of Singleton under Jboss5.1 with EJB3.0 Annotations.

  1. Hey I am so grateful I found your site, I really found you by error, while I was researching on Yahoo for something else, Nonetheless I am here now and would just like to say thanks a lot for a incredible post and a all round enjoyable blog (I also love the theme/design), I don’t have time to browse it all at the moment but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the fantastic job.

Leave a Reply