0
votes

Message driven beans are wonderful Java EE technology pieces that allow you to handle and process data concurrently, one message - one task - one thread. However sometimes there is need to keep the state of previous messages so that after collecting few or dozens of messages whole set of these messages might be processed together inside the single the same thread. The point is MDB after receiving message should avoid next steps, somehow informs that for example next 4 messages in the JMS queue should be saved somewhere, and after that after receiving 5th message these 5 messages should be used fo some calculation together. The question is: what kind of technology should be used to handle this scenario? Singleton bean? IMDG (for example JBOSS Cache, Infinispan)? What is the best practise?

EDIT: Unfortunatelly (almost) always two JMS messages are handled by two different instances of Message Driven Bean and each instance of MDB uses different instance of any session bean (stateful or stateless).

    @MessageDriven(activationConfig = {...})
    public class SomeMDB implements MessageListener {
       @EJB AnyService service
    }

In that such of case, even if AnyService is a stateful bean, each message has its own instance of SomeMDB and instance of AnyService. Correct me if I am wrong.

2

2 Answers

0
votes

My best guess would be to invoke a stateful session bean from your message driven been.

Since stateful session beans can keep their memory you can check how many messages have been received using a static counter.

Hope it helps!

0
votes

If you use stateful session beans, if the EJB server goes down, we will loose all of the previous messages, which causes message loss.

Rather, In my opinion, we can achieve your requirement using single MDB + Database

We can follow the below steps:

(1.0) MDB Receives the message

(2.0) Check if the required amount (5 or 10 what ever) of messages already exists in the database

(2.1) If YES, Retrieve the existing messages from the database and process them.

(2.2) If NO, Persist the message to the Database

P.S.: You might need to clean up the messages in the database on daily basis or after processing them successfully.