user3203425
user3203425

Reputation: 3059

How do we start a thread from a servlet?

What's the recommended way of starting a thread from a servlet?

Example: One user posts a new chat message to a game room. I want to send a push notification to all other players connected to the room, but it doesn't have to happen synchronously. Something like:

public MyChatServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response) 
    {
        // Update the database with the new chat message.
        final String msg = ...;
        putMsgInDatabaseForGameroom(msg);

        // Now spawn a thread which will deal with communicating
        // with apple's apns service, this can be done async.
        new Thread() {
            public void run() {
                talkToApple(msg);
                someOtherUnimportantStuff(msg);
            }
        }.start();

        // We can send a reply back to the caller now.
        // ...
    }
}

I'm using Jetty, but I don't know if the web container really matters in this case.

Thanks

Upvotes: 2

Views: 463

Answers (4)

JDGuide
JDGuide

Reputation: 6525

What's the recommended way of starting a thread from a servlet?

You should be very careful when writing the threading program in servlet. Because it may causes errors (like memory leaks or missing synchronization) can cause bugs that are very hard to reproduce, or bring down the whole server.

You can start the thread by using start() method.

As per my knowledge , I would recommend startAsync (servlet 3.0). I got some helpful link for you Click.

but I don't know if the web container really matters in this case.

Yes it matters.Most webservers (Java and otherwise, including JBoss) follow a "one thread per request" model, i.e. each HTTP request is fully processed by exactly one thread. This thread will often spend most of the time waiting for things like DB requests. The web container will create new threads as necessary.

Hope it will help you.

Upvotes: 1

Eyal Schneider
Eyal Schneider

Reputation: 22446

I would use a ThreadPoolExecutor and submit the tasks to it. The executor can be configured with a fixed/varying number of threads, and with a work queue that can be bounded or not.

The advantages:

  • The total number of threads (as well as the queue size) can be bounded, so you have good control on resource consumption.
  • Threads are pooled, eliminating the overhead of thread starting per request
  • You can choose a task rejection policy (Occurs when the pool is at full capacity)
  • You can easily monitor the load on the pool
  • The executor mechanism supports convenient ways of tracking the asynchronous operation (using Future)

Upvotes: 0

injecteer
injecteer

Reputation: 20699

One option would be to use ExecutorService and it's implementations like ThreadPoolExecutor , to re-use the pooled threads thus reducing the creation overhead.

You can use also JMS for queuing you tasks to be executed later.

Upvotes: 0

PeterMmm
PeterMmm

Reputation: 24630

In general that is the way. You can start any thread anywhere in a servlet web application.

But in particulary, you should protect your JVM from starting too much threads on any HTTP request. Someone may request a lot ( or very very much ) and propably at some point your JVM will stop with out of memory or something similiar.

So better choice is to use one of the queues found in the java.util.concurrent package.

Upvotes: 0

Related Questions