Question

I am trying to implement comet approach for Facebook like browser push notifications in following manner:

  1. HTTP request is made to a simple Servlet using AJAX, it gets submitted to java.util.concurrent.Executor (using AsyncContext) and HTTP thread gets freed immediately. This request is picked by a background thread.
  2. This background worker thread in the thread pool keeps checking for new notification every 30 seconds (Queries database). If there is any notification, a response it sent. Else after certain timeout i.e. 5 minutes, a "No Notification" response is sent. Client immediately makes a new request and the process is repeated.

Problem here is that I am using Thread.sleep(30000) for periodically checking the data. There is still one thread occupied per request. This time (30 sec) is wasted and the thread remains un-available to cater any other request.

Is there any technique which I can use, to return the thread to pool immediately after it has checked for new notification? And then some other available thread from the pool does the same after 30 secs to check notifications and so on?

Code goes like this:

// Creation of a global async Executor on ServletContextListener. contextInitialized
   Executor executor =
                    new ThreadPoolExecutor(1, 1, 50000L,
                        TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>(100));

// Delegate the request to async thread 
   executor.execute(new RunnableClass(asyncContext));



 // In RunnableClass.run() method

    while(timeout5Min)
    {
       boolean newNotificationPresent = checkIfNotificationPresent(reqId);

       if(!newNotificationPresent)
         Thread.sleep(30000);
    }

 // send response

Can ScheduledThreadPoolExecutor somehow be used in such case? Any other technique?

No correct solution

OTHER TIPS

If you are looking for Thread efficiency, you should look at actors. Have a look at Akka

Otherwise, don't sleep, schedule a recheck using a java.util.Timer

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