How to create a MDB 3.0 singleton ?
You can specify the maximum number of JMS Sessions that are available to concurrently deliver messages to an MDB using the maxSession property. Here is an example:
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "maxSessions", propertyValue = "1"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "TASK.QUEUE")
})
public class BuildTasksMessageListener implements MessageListener {
@Override
public void onMessage(Message message) {
try {
doSomethingUseful();
} catch (JMSException e) {
// Why can't I throw a JMS Exception
throw new RuntimeException(e);
}
}
// This is the only "useful" code in the class
private void doSomethingUseful() {
}
}
You can also set the max-session attribute in the XML descriptor:
<activation-config>
<activation-config-property>
<activation-config-property-name>maxSession</activation-config-property-name>
<activation-config-property-value>1</activation-config-property-value>
</activation-config-property>
</activation-config>
By setting max-session to 1 will essentially give you a singleton MDB.
Warning: a Message Driven Bean configured to run as Singleton can soon become a bottleneck for your application. If you want a higher scalability / availability of your MDB you should consider increasing the number of MDB session instead.
Older JBoss versions
If you are running JBoss 4/5/6 you can configure this at EJB container level by changing the server/$/deploy/ejb3-interceptors-aop.xml file:
<annotation expr="!class(@org.jboss.annotation.ejb.DefaultActivationSpecs)">
@org.jboss.annotation.ejb.DefaultActivationSpecs (value={@~ActivationConfigProperty(propertyName = "maxSession", propertyValue = "1")})
</annotation>
This will set the default for all message driven beans.
Recommended Articles
Learn How to Code Simple Message-Driven Bean (MDB) and Client Interaction in Enterprise Java
Master coding a simple MDB and Client interaction for asynchronous messaging with this tutorial. #EnterpriseJava #MDB #CloudNative
Create Type Safe Instances Using EJB QL in Enterprise Java
Learn how to use EJB QL for type-safe object creation and property selection in Enterprise Java. #EnterpriseJava #EJBQL #TypeSafety
Mastering EJB 3: Simplifying Enterprise Java Development with Annotations
Learn how to simplify your EJB 3 development process using metadata annotations and declarative programming. Discover the power of session beans, stateless beans, and more in this comprehensive guide.
WildFly 27: Configure Distributed EJB Timers for Scalability
Learn how to configure WildFly 27's new distributed EJB Timers for optimal scalability. #WildFly #JavaEE #EJB #Infinispan