Question

Trying to implement simple Ajax polling without Websockets or anything else.

Now, my ajax looks like this:

// start simple long term polling
(function poll(){
    $.ajax({ 
        url: "/app/api/ltp/receive", 
        success: function(data) {
            // do some stuff
        },
        dataType: "json", 
        complete: poll, 
        timeout: 30000 // again and again
    });
})();

The problem is on server side:

I have to check message queue for new messages and block some time before checking again. When there is a message, I can send json back to the client, holding the connection with an extra long timeout.

But as I know, in CDI I should never use Thread.sleep(ms) to block, right? What can I do instead?

Was it helpful?

Solution

This article might be helpful:

Asynchronous processing support in Servlet 3.0 by Dr. Xinyu Liu

In short, it explains that for Ajax (Comet, Long Polling) the new Async support in Servlet 3.0 specification can be used to implement a delayed answer (HTTP response) when there are new messages available on the server.

Instead of sleeping, the code (on page 2) uses a ConcurrentLinkedQueue to store messages, and then invokes its poll() method to wait for new messages.

This article also explains that this new Async support helps to reduce resource usage, because the original threads initiating the request/response loop are immediately returned to the thread pool and ready to serve other tasks.

At the moment I am working on a Ajax long polling demo based on GlassFish 4, a message driven bean (JMS), and JavaServer Faces, so I found your question here, and will come back if I find more helpful information or example code.

See also: I don't understand Async support in servlets 3.0 API

OTHER TIPS

What makes you believe that you need to have a sleep in your CDI bean? Shouldn't the endpoint just react to whatever messages its getting, by looking in whatever message queue you're pulling these messages from?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top