Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
Oh Chin Boon Avatar asked Dec 10 '22 07:12

Oh Chin Boon


1 Answers

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!

like image 117
home Avatar answered Mar 30 '23 00:03

home