Search code examples
javajakarta-eejbossejbejb-3.0

Solution for Thread.sleep inside EJB


I am using jboss5.1, EJB3.0 and standalone java application as a 'subscriber'

I have mechanism which publish messages via jms Topic to subscribers. when subscriber get the message it need to do few operations until it will start listening again for a future messages.

the problem is that if a subscriber get a message from the Topic it will need to get back fast enough to listen for further messages(else it will miss it in a case another message will be published)

So my solution is to putThread.sleep() for couple of seconds inside the ejb publisher.

This way ill make sure that all subscribers went back to listen before a new message will be published.

I know that using Thread inside EJB'S is not recommended.

any solution for that scenario?

thanks, ray.


Solution

  • OK, so your problem is actually that you stop listening to the JMS queue when you process a message and then you register yourself back. Of course, you could then miss messages while your processing a previous one.

    I would suggest to never unregister yourself from the JMS queue and in order to ensure that you process a single message at a time, you could use a single thread pool where you push your processing.

    For example, if previously you had something like this:

    public void onNewJMSMessage(JMSMessage message) {
        unregisterMySelf();
        processMessage(message);
        registerMySelf();
    }
    

    Use this instead:

    Initiate a class member like this:

    private ExecutorsService processingPool = Executors.newSingleThreadExecutor();
    

    and

    public void onNewJMSMessage(final JMSMessage message) {
        processingPool.submit(new Runnable() {
    
             @Override
             public void run() {
                  processMessage(message);
             }
        });
    }
    

    This will guarantee that only a single message at a time is processed (if the enclosing class is unique, otherwise you will have to setup a singleton to ensure the uniqueness of the Single-thread pool).

    Having done that, this will mainly allow you to remove that Thread.sleep in your EJB which is evil and sources of all kind of headaches.