Behavior of Java's ScheduledExecutorService.scheduleAtFixedRate() - java

I have a question regarding the scheduleAtFixedRate() method on ScheduledExecutorService in Java 6.
[edit: the Javadoc for 1.6 is more complete than that for 1.5. See comment below]
Given that:
the ScheduledExecutorService is constructed with N = 1 thread in the pool
the fixed-rate is a period of T seconds
no initial delay
What happens in this case (times are not meant to be absolute, in the real-time sense):
at time T, the service kicks off a Runnable task, "task1"
at time 2T, task1 has not yet completed, and service is scheduled to fire
Is the service guaranteed to do any of the following?
(a) at 2T, kick off a Runnable task, "task2" (recall N = 1)
(b) block until task1 is finished
(c) skip this time and try again at 3T
(d) behavior is undefined
Or something else? Does the answer change if N > 1 ?

The answer is
(b) block until task1 is finished
and that is regardless of number of threads of the executor (task2 might even be not submitted).
The doc says:
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
(BTW, since there's no intial delay, "task1" will kickoff right away as doc`ed:
executions will commence after initialDelay
).

From the documentation that you linked...
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

Related

ScheduledExecutorService task that blocks for longer than its run interval

Question about ScheduledExecutorService.shceduleAtFixedRate - I schedule taskA to run every 500 millis, which blocks for 1000 millis. Now subsequent executions aren't gonna wait the extra 500 millis, but rather commence immediately after the previous one.
taskA acquires an intrinsic lock, which is also (attempted) acquired by a different thread. Since intrinsic locks have no fairness guarantees this thread is running a risk of starvation, so here's my question: Is there a good/clean way to avoid this risk? E.g. schedule the task to run every 1500 millis (doesn't sound very waterproof)? Or do we expect the lock acquisition to exhibit a kind of "amortized fairness"?
Yes, you can use scheduleWithFixedDelay:
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
So the delay you give is the time between end of last end start of next - ie no overlap between runs.

Behavior of ScheduledExecutorService

I've been wondering about specific case around ScheduledExecutorService in java.
Let,
ScheduledExecutorService = new ScheduledThreadPoolExecutor(2);
service.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
//Some task taking longer than schedule period to finish executing.
}
},initialDelay,period,TimeUnit.SECONDS);
in this case, say period is 4 seconds. When the schedular starts to execute after initialdelay, task will be blocked inside while(true) inifinite loop.
My question is after each 4 seconds does a task get scheduled disregarding the execution(unfinished) of previous round of task? Because if this is the case this code will crash eventually after running out of memory.
Help is appreciated.
Thank you.
From the javadoc of scheduleAtFixedRate():
If any execution of this task takes longer than its period, then
subsequent executions may start late, but will not concurrently
execute.
Meaning the task will be started once, but since it never finishes there won't be other invocations. You'll just be wasting one thread in the pool.
The same applies to scheduleWithFixedDelay() since the delay is counted from the time when the previous execution finishes (and since it doesn't finish, no next execution can happen).

schedule on task at a time - java

I have a task that is scheduled periodically. Sometime it can take longer than expected.
I am trying to find a way to make sure that scheduling will be canceled in case the task is already running. All mechanisms I check will make the task wait and run it after the first finish
locking ofcourse will do the job but I'm looking of something more high level
Any Idea
You can use ScheduledExecutorService. scheduleAtFixedRate is probably what you want as it will wait for your tasks to finish, iff one takes longer than the rate you specify:
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
Example:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(() -> {
// Body will be executed every second unless the previous task hasn't finished.
}, 0L, 1L, TimeUnit.SECONDS);
There is something called scheduleAtFixedRate and scheduleAtFixedDelay.
scheduleAtFixedRate will start another process at defined time, so if previous process is not completed, two processes will be running and it might cause race condition of running same thing twice.
scheduleAtFixedDelay will start after fixed time once a task is completed.
scheduleAtFixedRate vs scheduleWithFixedDelay
In Spring you can do this by using annotation:-
#Scheduled(fixedDelay =30000)
http://howtodoinjava.com/spring/spring-core/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/
do you know Apache Camel framework?
It has a module called quartz2 and has a much possibility to scheduling any task.
try read this page:
http://camel.apache.org/quartz2.html

Understanding the ScheduledThreadPoolExecutor

I know that I must use this instead of java.util.Timer because of various reasons. So, to study this I was looking at the docs and I have a few questions:
How does scheduleWithFixedDelay() work ? My understanding is this: It first executes a task after a given delay. Once the task is done, it waits for the specified time and then executes the task again.
What happens when I submit a task to scheduleAtFixedRate() that takes a lot more time to execute than the specified delay ? Like I want the task to execute every 5 seconds but it takes 10 seconds to complete. My understanding is that the task will be held in a queue and will be executed once a core thread is available
Here is my understanding of how scheduleWithFixedDelay() and scheduleAtFixedRate() differ: scheduleWithFixedDelay() waits for the task to finish executing, waits for the specified time and then fires the task again where as scheduleAtFixedRate will just keep firing the task without caring if it has completed or not. Correct?
Correct.
Not quite. If a fixed-rate task takes longer than its period, it will run again immediately upon completion, but the next run is not waiting for a thread. See below.
A fixed-rate task does care whether its previous run has completed, just like a fixed-delay task. Per the documentation, "If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute."
Think of it this way:
For a fixed-delay task, you specify a period which will be the exact amount of time between runs. The actual duration of the task has no effect on the delay.
For a fixed-rate task, you specify a period which will be the maximum amount of time between runs. If the actual duration of the task is longer than the period, the rate is reduced, and there is effectively no delay.

Java: SingleThreadScheduledExecutor & java.util.concurrent.RejectedExecutionException

I am having this problem, I have
private ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
and task which is created every 50 millliseconds:
executor.scheduleAtFixedRate(myTask, 0, 50, TimeUnit.MILLISECONDS);
myTask sometimes take a while to complete (like 2-3 seconds or so), but newSingleThreadScheduledExecutor guarantees that next scheduled myTask will wait until the current one completes.
However, I get this error from time to time:
execute: java.util.concurrent.RejectedExecutionException
What should I do? Thanks
Consider what the executor is doing. It is running a single task every 50 milliseconds, as per your instructions. Assuming this task takes less than 50 milliseconds to run, then everything is fine. However, every so often it takes 2-3 seconds to run. When this happens, the executor still tries to execute every 50 milliseconds, but because it only has a single thread, it can't, and rejects those executions that are being triggered while your long-running task is still going. This causes the exception you see.
You have two choices to fix this (assuming you want to stick with a single thread):
Use scheduleWithFixedDelay rather than scheduleAtFixedRate. If you read the javadoc carefully, you'll see that scheduleWithFixedDelay will wait 50 milliseconds between the finishing of one task and the start of the next, so it will never "overlap", even if one of them takes a long time. In contrast, scheduleAtFixedRate will try to execute every 50 milliseconds, regardless of how long each one takes.
Change the way that the executor handles failures to execute. The default is to log an exception, but you can tell it to ignore it, for example. Take a look at the subclasses of of java.util.concurrent.RejectedExecutionHandler, for example DiscardPolicy, which just silently drops the task that can't be run. You can use these by directly constructing ScheduledThreadPoolExecutor and passing in the handler to the constructor, rather than using the Executors factory class.
I suspect option (1) is what you want.
This exception will be thrown when either:
You have shutdown the Executor
The Executor's bounds for its work queue or maximum threads have been exceeded.
I assume the latter is happening. When you execute your task and it takes a long time then subsequent scheduled tasks can not be run because there are not enough threads available in the pool.
Either:
Use use a larger pool size or use cachedThreadPool
Change the rejection policy to for example use ThreadPoolExecutor.CallerRunsPolicy
Create a separate Executor for running the long run tasks and run these from your scheduled task. In actual fact you can do this using the same Executor instance providing that you increase the pool size.
See also ThreadPoolExecutor javadoc
With Java 7 both of them will wait till the first execution is ready and then start the next!
check here:
http://download.java.net/jdk7/archive/b123/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
or here:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

Categories