servlet multithreading
I understand that Servlet requests are by default multithreaded. I created a simple servlet using NetBeans, and it appears to be single threaded, on both Tomcat and JBoss.
I tested it using this code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("access processRequest: " + this + " threadID: " + Thread.currentThread().getId());
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(OctaveServlet.class.getName()).log(Level.SEVERE, null, e开发者_如何学JAVAx);
}
System.out.println("exit processRequest: " + this + " threadID: " + Thread.currentThread().getId());
}
(processRequest is called from doGet)
I accessed this from 2 tabs in my browser almost at the same time, and if multithreading would have worked, I'd expect it to print the "access" with 2 different threads ID's, and then the "exit" of both threads. Instead, I get this output:
14:53:41,839 INFO [stdout] (http--127.0.0.1-8080-1) access processRequest: OctaveServlet@31ccfe threadID: 34 14:53:46,840 INFO [stdout] (http--127.0.0.1-8080-1) exit processRequest: OctaveServlet@31ccfe threadID: 34 14:53:46,867 INFO [stdout] (http--127.0.0.1-8080-1) access processRequest: OctaveServlet@31ccfe threadID: 34 14:53:51,867 INFO [stdout] (http--127.0.0.1-8080-1) exit processRequest: OctaveServlet@31ccfe threadID: 34
As you can see it was just one thread. Needless to say, I'm not implementing the SingleThreadModel.
Here are details of my system: NetBeans 7.0.1, JVM: Sun java 1.6.0_26, Tomcat 7.0.14, JBoss AS 7, Ubuntu 11.04
Many thanks for any help,
Oded.
It's using one thread per HTTP connection (it's not exactly that when the server uses NIO, but you got the point). Your browser is apparently using the same HTTP connection in both tabs. Spawn two different browser instances (e.g. Firefox and Chrome) and you'll see that it works the way you expected.
精彩评论