wood burning stoves
The moose likes Servlets and the fly likes about instance of servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "about instance of servlet" Watch "about instance of servlet" New topic

about instance of servlet

david hu
Ranch Hand

Joined: Jul 20, 2001
Posts: 143
Suppose I use one browser window to connect to the servlet and use another browser window or another machine to connect to the same servlet at the same time(both connection may continue for long time), will the server create two instance of the servlet to response the request or just one instance? Another question is will the server create two threads to respond the two request?
I am a little confusing about it. Wish someone can give me some help
Ranch Hand

Joined: Jul 06, 2001
Posts: 257
Sometimes it depends on the servlet engine or application server you are using, but in most cases, there exists only 1 instance of the servlet, and this single instance services all requests. This is why it's important to make your servlets thread-safe. And yes, if you access the servlet from 2 different contexts, or even the same context (same machine), at the same time, then the server will use two different threads to access the servlet. And again, it is for this reason that you must ensure your servlet is thread-safe.
david hu
Ranch Hand

Joined: Jul 20, 2001
Posts: 143
I do not quite understand from where or how the servlet spawn a new thread. Since you know that in the servlet I wrote, there's no statement in it that explicitly spawn a new thread to respond a new request.
How does it work?
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Reading the servlet spec will clear up a lot of your questions.

Specifically, I've copied some of it here

SECTION SRV 2.2 So that describes how many instances of your servlet are hanging around. In most cases, just the one. So concurrent requests must be handled by one servlet, and this is were multiple threads comes in.

From SECTION SRV. was the long answer. The short answer is: The container is doing the threading, not you. You simply need to write your servlet so that it can handle these multiple threads.
subject: about instance of servlet
It's not a secret anymore!