简体   繁体   中英

Thread Delay using scheduler or Thread.Sleep

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.

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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