Luigi Cortese
Luigi Cortese

Reputation: 11131

Why is this servlet using multiple threads in its "Thread Per Connection" policy?

Premise: this question is related to a previous longer one, I think it's better posting a new short question rather than making the other one even longer. I have already read this, this, this, this and many others, and they didn't help. My question is not a duplicate of any of these, please don't vote to close, just don't answer if not interested.

I have this doGet() method in a servlet

protected void doGet(/*params*/)/*exceptions*/{

    System.out.print("Thread:"+Thread.currentThread().getName()+"    ");
    System.out.print("Session:"+request.getSession().getId()+"    ");
    System.out.println("start...");

    try {Thread.sleep(4000);} 
    catch (InterruptedException e) {}

    System.out.print("Thread:"+Thread.currentThread().getName()+"    ");
    System.out.print("Session:"+request.getSession().getId()+"    ");
    System.out.println("...end");

}

This is my output when I invoke the servlet from 3 tabs of the same browser (almost) simultaneously

18:09:17,080 [...] Thread:default task-15    Session:_5axg3aG4vaOf-5qxWJ5TWYk    start...
18:09:21,081 [...] Thread:default task-15    Session:_5axg3aG4vaOf-5qxWJ5TWYk    ...end
18:09:21,088 [...] Thread:default task-16    Session:KYQf66vtc4ezaUD1vrGIMQje    start...
18:09:25,090 [...] Thread:default task-16    Session:KYQf66vtc4ezaUD1vrGIMQje    ...end
18:09:25,101 [...] Thread:default task-17    Session:wyViZoHMGL1Mb8f9BCXO8aJK    start...
18:09:29,102 [...] Thread:default task-17    Session:wyViZoHMGL1Mb8f9BCXO8aJK    ...end

My understanding is that the 3 requests are processed sequentially because the client is using the same connection for multiple requests and the server is using a Thread Per Connection policy.

But it seems like a different thread is being used every time (15, 16 and 17). Why is this happening? What am I getting wrong? (Wildfly 8 + Chrome)

Upvotes: 0

Views: 654

Answers (1)

Manish Maheshwari
Manish Maheshwari

Reputation: 4134

Chrome creates a new process per tab. It will create a new TCP connection from each tab, to the servlet. You can validate this by printing the clients port in your servlet code.

Since you have 3 TCP connections, and wildfly with a Thread Per Connection policy, you are witnessing expected results. One thread per connection :)

Upvotes: 1

Related Questions