我们在Spring(Tomcat内部)中使用ThreadPoolTaskExecutor
来启动侦听端口(3001
)的并发服务器。
我们的代码看起来有点像:
....
ServerSocket listener = new ServerSocket(port);
Socket server;
while (true) {
PollingTask pollingTask;
server = listener.accept();
log.info ("Got a new connection, spawning a thread: " + i++);
taskExecutor.execute(new PollingTask(server, i));
}
PollingTask的代码类似于:
....
PollingTask(Socket server, int counter) {
this.server = server;
this.counter = counter;
}
public void run() {
input = "";
try {
log.info ("New runnable thread: " + counter);
}
}
....
Spring配置如下:
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="100" />
<property name="maxPoolSize" value="200" />
<property name="queueCapacity" value="50" />
<property name="keepAliveSeconds" value="600" />
</bean>
这个特殊的bean在启动时启动,然后我们尝试使用telnet连接到端口(3001
)。
有趣的是,我们在日志中看到了:
Got a new connection, spawning a thread: 0
....
然而,在实际显示之前,它一直到48左右:
New runnable thread: 0
....
我如何说服Spring立即处理线程/任务,而不是等待?
(我尝试使用queueCapacity
)