Prateek Shrivastava
Prateek Shrivastava

Reputation: 480

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.

Upvotes: 5

Views: 2841

Answers (2)

李宏林
李宏林

Reputation: 1

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;

Upvotes: 0

dogant
dogant

Reputation: 1386

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.

Upvotes: 3

Related Questions