4

For an object to be runnable, it needs to implement the Runnable interface or extend the Thread class, however, it does not seem that HttpServlet does any of these.

How come HttpServlet can be threaded or have i mistaken?

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • 1
    Just because something is "thread safe" (I am taking this as the meaing of "thread-able") doesn't mean it provides an entry-point for a thread. –  Jul 31 '11 at 08:14
  • 2
    Related: http://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables – BalusC Aug 01 '11 at 02:44

3 Answers3

14

The Servlet itself is not a thread. The container maintains one instance of the servlet class and each request (thread) calls the same servlet object. So the servlet instances is shared across threads. In pseudo code it may look like this:

class ServerThread extends Thread {

    private javax.servlet.Servlet servlet;
    private javax.servlet.ServletRequest req;
    private javax.servlet.ServletResponse res;

    public ServerThread(javax.servlet.Servlet servlet, /* request and response */) {
        this.servlet = servlet;
        this.req = req;
        this.res = res;
    }

    @Override
    public void run() {
        this.servlet.service(req, resp);
    }

}

No question, in reality it will be much, much, much more complex :-)

BTW: That's the reason your servlet classes have to be thread safe!

home
  • 12,468
  • 5
  • 46
  • 54
  • 1
    Also, are you saying that the Servlet is a singleton, or is it container-vendor independent? – Oh Chin Boon Jul 31 '11 at 09:09
  • 1
    @Chris Boon: I'm pretty sure it is a singleton, but I do not know how container providers (like Tomcat) handle that... they may have introduced some _crazy_ tricks. But yes, you should treat it as a singleton. – home Jul 31 '11 at 11:04
1

Any class in Java may be executed on any thread, unless explicitly prohibited at run time by some sort of check. Without knowing the specifics of HttpServlet, I imagine that somewhere you encountered a statement to the effect of HttpServlet being thread-safe. If this is the case, that means a given instance of the class (or static methods of the class) can be safely used from any number of threads at once.

Also, the reason that Thread is a runnable is because it implements the Runnable interface; any class may do so. The notable aspect of Thread's run() method is that when a Thread instance is started, its run() method is called on a separate thread.

Joshua Kaplan
  • 843
  • 5
  • 9
0

Anything is thread able. An EJB for spring beans are not threads themselves, but they run in multi threaded environments and hence they are thread able.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186