Thread Delay using scheduler or Thread.Sleep

早过忘川 提交于 2021-01-27 10:51:37

问题


In my application I am calling third part vendor web-service. I need to delay my thread processing to achieve required throughput supported by vendor webservice.

I have two options 1. Use Thread.Sleep 2. use ScheduledThreadPoolExecutor as mentioned in the post How to start a thread after specified time delay in java

Wanted to know which is better option as we are sending time critical information(Text Message) using Vendor webservice. Any help is appreciated.


回答1:


They're pretty much the same as ScheduledThreadPoolExecutor.scheduleWithFixedDelay encapsulates the sleep call.

Since the delay is 100ms performance difference is kind of negligible. I'd go with ScheduledThreadPoolExecutor.scheduleWithFixedDelay due to pooled threads. The amount of load put on the system would be manageable, you wouldn't have multiple threads waking up from sleep together to compete for resources.

Also from the doc

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.




回答2:


use the scheduler method, you can select fixed-rate or fixed-delay. look the source code:

    /**
     * Period in nanoseconds for repeating tasks.  A positive
     * value indicates fixed-rate execution.  A negative value
     * indicates fixed-delay execution.  A value of 0 indicates a
     * non-repeating task.
     */
    private final long period;


来源:https://stackoverflow.com/questions/31882624/thread-delay-using-scheduler-or-thread-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!