4

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.

Community
  • 1
  • 1
Prateek Shrivastava
  • 450
  • 2
  • 5
  • 17

2 Answers2

3

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.

dogant
  • 1,376
  • 1
  • 10
  • 23
  • Not the same. `Thread.sleep()` is a low-level primitive. `ScheduledThreadPoolExecutor` is a higher-level abstraction. Any time you find yourself wanting to call such a low-level thing as `sleep()`, you should stop and ask, "Am I re-inventing a wheel?" 'cause you probably are. – Solomon Slow Aug 07 '15 at 17:00
  • 1
    yes but we're talking about 100ms delay here and performance difference would be at nano seconds level or at worst micro seconds level. It's pretty much negligible. – dogant Aug 07 '15 at 17:02
  • I'm not talking about performance. I'm talking about not writing gratuitous lines of code. Each new line of code that you write is a liability. If you can get the job done by re-using code that already exists, you'll come out ahead. If you need to schedule events to happen at predictable future times, use a `ScheduledThreadPoolExecutor` instead of writing your own. If you need to prevent something from happening too often, use a `com.google.common.util.concurrent.RateLimiter` instead of writing your own, etc., etc. – Solomon Slow Aug 07 '15 at 17:27
0

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;
李宏林
  • 1
  • 1