1

I have a webservice which calls this method

public void process(Incoming incoming) {
   // code to persist data
   ...
   Thread.sleep(20000);
   // check persisted data and if status != CANCELLED then process
}

Requirement is that I have to wait 20 seconds (as business has high probability to send cancel request within 20 seconds in which case we should not process).

I understand that Thread.sleep() doesn't even bother the cpu until time's up.

  • But concern is, since it is being called from a webservice, these Threads might be from a pool of some sort and might exhaust if lot of requests come?
  • Or do new servlet containers automatically create extra threads if exhausted and we can write this kind of code without worrying about these things?
  • Does scheduling an asynchronous task which runs after 20 seconds a better option? Here also, we have to have a Thread pool to execute these tasks anyways.
4

3 回答 3

3

调度一个在 20 秒后运行的异步任务是一个更好的选择吗?在这里,无论如何,我们必须有一个线程池来执行这些任务。

是的,这是一个更好的选择,因为Thread.sleep(20000);每个请求都会阻塞一个线程。使用调度线程池,您将任务添加到某种队列,然后使用恒定数量的线程执行它们 - 因此不可能耗尽所有可用线程。

于 2017-07-24T08:47:08.697 回答
3

调度一个在 20 秒后运行的异步任务是一个更好的选择吗?在这里,无论如何,我们必须有一个线程池来执行这些任务。

如果您的最终用户/应用程序不需要来自 web 服务调用的任何结果,那么最好不要保留线程。你应该走异步的方式。

于 2017-07-24T08:27:47.987 回答
0

或者新的 servlet 容器是否会在用尽时自动创建额外的线程,我们可以编写这种代码而不用担心这些事情?

要自定义此线程池的大小,您应该为您的or文件中的server.tomcat.max-threads属性指定一个非零值。application.propertiesapplication.xml

于 2017-07-24T08:44:57.040 回答