开发者

HttpServlet does not implement runnable or extend thread, why is it thread-able?

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?


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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜