[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));
		}
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值