I go to the FTP each 2 mins to upload new files.
I implemented it with java.util.Timer. But after some time - several days or even week - it stops without any exception and without any reason.
I found thread:
Java unlimited thread stops after some time
But there is no particular solution in it.
I read about ScheduledExecutorService, but as far as I understand - it's the same as Timer.
Please give me some ideas!
You can try to set a default Exception handler using Thread.setDefaultUncaughtExceptionHandler() API in your main thread and try to log any throwable/exception that could get swallowed silently.
I just saw that no one have answered this question, maybe because this is a duplicate.
ScheduledExecutorService uses System.nanotime() and Java.util.Timer uses System.currentTimeMillis().
System.currentTimeMillis() depends up on system time and System.nanotime() gives nanoseconds since some fixed arbitrary initial time and is not related to system time. So any change in system time (due to NTP time correction or system stand-by) may or may not impact Timer execution. This would be the reason that your timer fails.
For more details please refer - What should Timertask.scheduleAtFixedRate do if the clock changes?
Related
I have a Spring Boot application that uses a #Scheduled annotation with a fixed delay. The annotation is used in different classes with different delays. However, at midnight every day all scheduled tasks stop running.
Does anyone know why this might be happening? I can't find any explanation online.
(I am using version 2.0.2.RELEASE of Spring Boot and 5.0.6.RELEASE of Spring Core.)
Thanks in advance!
I'm not sure what do you mean about stopping running.
But the first work you need to do is starting your schedules on different threads and put them into a queue.
If stopping means suspending for a while,then you create a new schedule that make other schedules sleep some time at midnight.Maybe the new schedule should have be started when the thread are sleeping,and the way to prevent is to make sure only one schedule(I mean same kind of schedule) could be put in the queue at the same time.
If you just mean kill all other schedule at midnight,you just need to start your midnight schedules and kill others.
So sorry about my poor English,hope this could help you.
#Scheduled(fixedDelay = 1000)
void scheduleFixedDelayTask() {
System.out.println(
"Fixed delay task - " + System.currentTimeMillis() /
1000);
}
In this case, the duration between the end of last execution and the start of next execution is fixed. The task always waits until the previous one is finished.
This option should be used when it’s mandatory that the previous execution is completed before running again.
So maintain the delay such a way that the previous execution completed.
Hope it helps.
Thanks to everyone who replied.
As it turns out, this was not an issue with Spring. It appeared the tasks stopped because the logs stopped. What really happened was that our scripts that tail the logs were not smart enough to handle log files that roll at midnight (face palm).
I have one method execute(data) which takes considerable time (depending on data like 10 seconds or 20 seconds), it has timeout feature which is 30 seconds default. I want to test that method. One way of doing it is to collect enough data which lasts more than 30 seconds and then see whether I get timeout exception. Other way of doing it is to use threads. What I intend to do is to run method for some milliseconds and then put thread on wait before I get timeout exception or make it last for some seconds.Can any one please suggest how can I achieve that.
You should walk through the Java Threads Tutorial (Concurrency). Any answer on Stack Overflow would need to be really long to help you here, and the Threads/Concurrency tutorials already cover this well.
http://docs.oracle.com/javase/tutorial/essential/concurrency/
You could use
Thread.sleep( millis );
to put the thread to sleep for the required time.
Or, you could put your data processing code into a loop, so that it processes it multiple times. This would recreate the scenario of the thread actually processing data for longer than 30 seconds.
Or, you could test your code with a shorter timeout value.
We all know of sleep method available in java threads..
I understand that the precision in timing depends on the precision of hardware clock in the system..
So my question is how accurate is this method or better say what is the error in milliseconds or nanoseconds considering a general pc.
My requirement its to synchronise data transfer using sleep for timing.. The data is to be sent in fixed in intervals (10-20 millis) and if there is a delay of more than 1sec due to successive error in timing it may be bad !
So is it advisable to use the also method?
Sleep is not the thing you want, as in here.
I suggest to read through this.
If you need to synchronize data, I suggest you do this yourself rather than relying on threads to wake up at preset times. i.e. use one thread to simulate when events occur, in the order you expect them to occur.
I'm using a ScheduledExecutorService to provide an update to a database every hour with the scheduleAtFixedRate method. The problem is that it gradually gets later - in long service I've been logging it and it's about a second a day.
I made a small class just to examine this aspect - seems to work fine when nothing is happening on the PC ( running WinXP ) but if things are going on it rapidly gets later. 18:00:00.5 last night was its first log and this morning was 09:00:00.5 then 10:00:05.9, 11:00:26.8, 12:00:45.3, 13:01:07.8...
I can attach the code although my example isn't the smallest.
Anyone else experienced this? Any ideas why this isn't working properly?
I can think of lots of ways around it but I'd really like to know why it doesn't work as advertised!
Thanks, Mike
This is normal AFAIK. With scheduleAtFixedRate, If any execution of this task takes longer than its period, then subsequent executions may start late. That being said, I'd recommend scheduleWithFixedDelay. This will ensure that tasks are carried out at the specified delay interval.
Does anyone know a Library which provides a Thread.sleep() for Java which has an error not higher than 1-2 Millisecond?
I tried a mixture of Sleep, error measurement and BusyWait but I don't get this reliable on different windows machines.
It can be a native implementation if the implementation is available for Linux and MacOS too.
EDIT
The link Nick provided ( http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks ) is a really good resource to understand the issues all kinds of timers/sleeps/clocks java has.
To improve granularity of sleep you can try the following from this Thread.sleep page.
Bugs with Thread.sleep() under Windows
If timing is crucial to your
application, then an inelegant but
practical way to get round these bugs
is to leave a daemon thread running
throughout the duration of your
application that simply sleeps for a
large prime number of milliseconds
(Long.MAX_VALUE will do). This way,
the interrupt period will be set once
per invocation of your application,
minimising the effect on the system
clock, and setting the sleep
granularity to 1ms even where the
default interrupt period isn't 15ms.
The page also mentions that it causes a system-wide change to Windows which may cause the user's clock to run fast due to this bug.
EDIT
More information about this is available
here and an associated bug report from Sun.
This is ~5 months late but might be useful for people reading this question. I found that java.util.concurrent.locks.LockSupport.parkNanos() does the same as Thread.sleep() but with nanosecond precision (in theory), and much better precision than Thread.sleep() in practice. This depends of course on the Java Runtime you're using, so YMMV.
Have a look: LockSupport.parkNanos
(I verified this on Sun's 1.6.0_16-b01 VM for Linux)
Unfortunately, as of Java 6 all java sleep-related methods on Windows OS [including LockSupport.awaitNanos()] are based on milliseconds, as mentioned by several people above.
One way of counting precise interval is a "spin-yield". Method System.nanoTime() gives you fairly precise relative time counter. Cost of this call depends on your hardware and lies somewhere 2000-50 nanos.
Here is suggested alternative to Thread.sleep():
public static void sleepNanos (long nanoDuration) throws InterruptedException {
final long end = System.nanoTime() + nanoDuration;
long timeLeft = nanoDuration;
do {
if (timeLeft > SLEEP_PRECISION)
Thread.sleep (1);
else
if (timeLeft > SPIN_YIELD_PRECISION)
Thread.yield();
timeLeft = end - System.nanoTime();
} while (timeLeft > 0);
}
This approach has one drawback - during last 2-3 milliseconds of the wait hit CPU core. Note that sleep()/yield() will share with other threads/processes. If you are willing to compromise a little of CPU this gives you very accurate sleep.
There are no good reasons to use Thread.sleep() in normal code - it is (almost) always an indication of a bad design. Most important is, that there is no gurantee that the thread will continue execution after the specified time, because the semantics of Thread.sleep() is just to stop execution for a given time, but not to continue immedeately after that period elapsed.
So, while I do not know what you try to achieve, I am quite sure you should use a timer instead.
JDK offers the Timer class.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html
Reading the docs clearly indicates that beyond the plumbing to make this a generalized framework, it uses nothing more sophisticated than a call to Object.wait(timeout):
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#wait(long)
So, you can probably cut the chase an just use Object#wait yourself.
Beyond those considerations, the fact remains that JVM can not guarantee time accuracy across platforms. (Read the docs on http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#currentTimeMillis())
I think you'll need to experiment with a compromise solution combining Timer and busy polling if you want to want the highest timing precision possible on your platform. Effectively Object#wait(1) -> System#nanoTime -> calculate delta -> [loop if necessary].
If you are willing to roll your own, JNI pretty much leaves it wide open for platform specific solutions. I am blissfully un-aware of Window's internals, but obviously if the host OS does provide sufficiently accurate realtime timer services, the barebones structure of setting up a timerRequest(timedelta, callback) native library shouldn't be beyond reach.
The Long.MAX_VALUE hack is the working solution.
I tried Object.wait(int milis) to replace Thread.sleep, but found that Object.wait is as accurate as Thread.sleep (10ms under Windows). Without the hack, both methods are not suitable for any animation
Use one of the Thread::join overrides on the current thread. You specify the number of milliseconds (and nanoseconds) to wait.
You could try using the new concurrency libraries. Something like:
private static final BlockingQueue SLEEPER = new ArrayBlockingQueue(1);
public static void main(String... args) throws InterruptedException {
for(int i=0;i<100;i++) {
long start = System.nanoTime();
SLEEPER.poll(2, TimeUnit.MILLISECONDS);
long time = System.nanoTime() - start;
System.out.printf("Sleep %5.1f%n", time/1e6);
}
}
This sleeps between 2.6 and 2.8 milliseconds.
Sounds like you need an implementation of real-time Java.