[spring mvc]tomcat生成处理线程执行spring mvc时的思考

tomcat官方文档描述如下:

Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCountattribute). Any further simultaneous requests will receive "connection refused" errors, until resources are available to process them.

spring mvc里面controller,service等bean默认是以单例模式运行。

对于一个浏览器请求,tomcat会指定(新建或者取空闲的)一个处理线程,在spring中不同的层面(MVC)都处于这个线程里面。

对于不同的请求,有可能是由同一个处理线程(tomcat处理线程池中)处理,但时间上不会有重叠。

所以在一个请求范围,使用ThreadLocal类也能够达到局部变量的效果。


模拟代码如下:

1.spring mvc controller

public class MockController {

	public void dosth() {
		Thread currThread = Thread.currentThread();
		String ci = ObjectUtil.obj2Str(currThread);
		// 显示当前线程(处理request的线程)
		System.out.println(ci);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

2.处理请求的线程

public class MockRequest extends Thread {
	private MockController con;

	public MockRequest(MockController con) {
		this.con = con;
	}

	public void run() {
		con.dosth();
	}
}

3.服务器线程池

public class MockServerThreadPool {

	public static void main(String[] args) {
		// 模拟spring mvc controller,单例模式
		MockController con = new MockController();
		// 模拟服务器处理请求的线程池,最大线程数量为3
		ExecutorService es = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 10; i++) {
			// 模拟请求
			es.execute(new MockRequest(con));
		}
	}

}



猜你喜欢

转载自blog.csdn.net/attwice/article/details/44672657
今日推荐