简体   繁体   English

在以下情况下建议使用Thread.sleep()

[英]Is using Thread.sleep() advisable in the below scenario

I have a webservice which calls this method 我有一个调用此方法的Web服务

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). 要求是我必须等待20秒(因为企业很有可能在20秒内发送取消请求,在这种情况下我们不应该处理)。

I understand that Thread.sleep() doesn't even bother the cpu until time's up. 我知道Thread.sleep()直到时间到了都不会打扰CPU。

  • 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? 但是值得关注的是,由于这些线程是从Web服务中调用的,因此这些线程可能来自某种类型的池,如果有大量请求来,这些线程可能会耗尽?
  • Or do new servlet containers automatically create extra threads if exhausted and we can write this kind of code without worrying about these things? 还是新的servlet容器是否在耗尽后自动创建额外的线程,而我们可以编写此类代码而不必担心这些事情?
  • Does scheduling an asynchronous task which runs after 20 seconds a better option? 安排在20秒后运行的异步任务是否更好? Here also, we have to have a Thread pool to execute these tasks anyways. 同样,在这里,我们必须有一个线程池来执行这些任务。

Does scheduling an asynchronous task which runs after 20 seconds a better option? 安排在20秒后运行的异步任务是否更好? Here also, we have to have a Thread pool to execute these tasks anyways. 同样,在这里,我们必须有一个线程池来执行这些任务。

If your end user/application does not need any outcome from the webservice call, then its a better idea not to hold the thread. 如果您的最终用户/应用程序不需要Web服务调用的任何结果,那么最好不要保留该线程。 You should go asynch way. 你应该去避难所。

Does scheduling an asynchronous task which runs after 20 seconds a better option? 安排在20秒后运行的异步任务是否更好? Here also, we have to have a Thread pool to execute these tasks anyway. 同样,在这里,我们必须有一个线程池来执行这些任务。

Yes, it is a better option, because with Thread.sleep(20000); 是的, 这是一个更好的选择,因为使用Thread.sleep(20000); you are blocking one thread per each request. 您将为每个请求阻塞一个线程。 With scheduled thread pool, you are adding tasks to some kind of queue, and later they are executed using the constant number of threads - so there is no possibility of exhausting all available threads. 使用调度的线程池,您可以将任务添加到某种队列中,然后使用恒定数量的线程执行任务-因此,不可能耗尽所有可用线程。

Or do new servlet containers automatically create extra threads if exhausted and we can write this kind of code without worrying about these things? 还是新的servlet容器是否在耗尽后自动创建额外的线程,而我们可以编写此类代码而不必担心这些事情?

To customise the size of this thread pool you should specify a non-zero value for the server.tomcat.max-threads property in your application.properties or application.xml file. 要自定义此线程池的大小,应在application.propertiesapplication.xml文件中为server.tomcat.max-threads属性指定一个非零值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM