can subsequent sleep() be skipped if the thread actually slept too long? - java

Let's assume that I have a following loop in a Thread (Let's call it Thread-A).
while (threadCondition) {
System.out.println(new Date());
Thread.sleep(1000);
}
and assume that other Thread-B will cause that the application is hanging up of the time >=2sec (because of some other Thread (Let's call it Thread-B, because of not enough CPU resources, low available memory, etc.)
Is it possible that when the Thread-A will come into action after those mentioned >=2 sec then the System.out.println(new Date()) will be executed twice one after another ('instantly', without the sleep), and will print the equal date (with the same number of millis) twice?

JVM does not guarantee the precision of time slept. It may wake after 996ms, 1003ms, or 2000ms - all are valid times
However, these sleep times are not guaranteed to be precise, because
they are limited by the facilities provided by the underlying OS.
Also, the sleep period can be terminated by interrupts, as we'll see
in a later section. In any case, you cannot assume that invoking sleep
will suspend the thread for precisely the time period specified --
source
No track is kept of the amount of time the thread really slept.
When another sleep() is encountered, the thread will wait another (and again, more or less) 1000ms before waking.
Since the sleep time is not precise, it is possible that at time 10.000 your app printed the date once, and at 10.981 it printed the same date again, evn though almost once second has passed.
Also: remember, that the sleep() method may be interrupted. If the exception handling code is in this loop, the sleep may get interrupted, exception swallowed and two dates printed.

Two calls to new Date() can give the same time if
if is in the same milli-second
if they are within the resolution of the clock. e.g. on Windows XP it is ~16 ms.
if time is changed by NTP or similar. e.g. time can go backwards and repeat.
if you use have byte code instrumentation to override the time. e.g. because you want a test driven clock.
if two thread start 2 seconds apart but finish at the same time, they can print the same time.
if thread B starts first and thread A starts after, thread B can print a time after thread A. Just because it starts earlier doesn't mean it will finish first.
new Date() will print the same date if they occur in the same second by default.

No, Thread.sleep(...) delays execution from when it is called for the specified amount of time. There's no internal counter keeping track of "current time" which can become out of sync due to the thread being pushed to the background temporarily, which seems to be what you're thinking.

I don't believe it is possible.
When application is hanging up because of any of the reasons you mentioned, it resumes executing from the line of code it stopped.
The fact that the code cause a hang that now may be redundant is irrelevant. You don't really expect the JVM to analyze your code...

Why not use System.nanoTime() ( ie the high-resolution performance counter in the PC) in place of date(). And if you put the sleep in an if and write the condition correctly it won't sleep the thread.

Related

Is the following while loop can be run more than one time?

I found a piece of code in Android src code that is very easy but I can't understand. The following code is a part of a bigger function (I don't think the other part is needed in order to get answer to my question)
timeoutMs = 10000 // timeoutMs is a function parameter but for the example i have initiated it here
if (timeoutMs > 0) {
long nowMs = SystemClock.uptimeMillis();
long deadlineMs = nowMs + timeoutMs;
while (!isDone() && nowMs < deadlineMs) {
wait(deadlineMs - nowMs);
nowMs = SystemClock.uptimeMillis();
}
}
It seems that the while loop will be run at most one time (depends on isDone value). Is there a situation the in the second loop the condition: nowMs < deadlineMs is true?
The way I see it, in the second condition they are already equal. Is that correct?
You seem to be labouring under a bit of a misconception: wait(100) does not wait 100 milliseconds! You'd think it does (it reads almost like english, literally: "Wait 100"), but it does not. That's not what wait is for. Thread.sleep(100) is java-ese for 'please wait for about 100 milliseconds'. wait(100) is java-ese for: Please wait until a notification arrives. However, try not to wait for longer than 100 milliseconds.
Let me explain: wait(x) is call you make on an object, it's not a utility method. You invoke it on something. In this case, as you just wrote wait and not foo.wait, therefore, you're invoking it on this; it's the exact same call as this.wait(100). This means two things: [A] this code must be within a syncronized(this) block, or the wait call will immediately throw an exception (why? Because the wait/notify system decrees it so - see the javadoc of these methods. The methods are in j.l.Object itself), and crucially [B], this code's primary purpose is to wait until another thread invokes x.notify() or x.notifyAll(), where x resolves to the same object identity that this resolves to in the pasted code. However, the 100 part is like a limit: Try not to wait any longer than that. In other words, the thread will go to sleep, and then wake back up after deadlineMs - nowMs milliseconds or sooner, if this is notify/notifyAlled.
It is possible/likely that you are thinking of Thread.sleep(100), which does indeed attempt to pause for about 100 milliseconds, and does not play any interruption games. There is no notify part to Thread.sleep, and you don't call sleep on any particular object. It's a static method. The code you pasted will run more than once-through the while loop if this gets notify/notifyAll-ed halfway through.
--EDIT--
Apparently a few further things are unclear:
"Isn't 100 ms is the maximum?"
No. For starters, CPUs and computers aren't usually that accurate unless you go out of your way for it, and shut down everything else it is doing. If after exactly 100ms the CPU is busy juggling a background install of an app update whilst applying HDR to that picture, and uploading another to gdrive, maybe right this very millisecond there isn't any time to run your stuff, maybe in about 5 milliseconds you get to go, at which point it'd be 105 milliseconds since.
Also, wait() implies a lock - the call crashes instantly if you don't have a lock. wait() relinquishes the lock, and before code continues, the lock must be re-acquired or the thread can't unpause. This can take a year if you're unlucky: All other threads that hold the lock must first progress to no longer holding it. This part doesn't apply to Thread.sleep, which is yet another reason why Thread.sleep is simply: "Wait x milliseconds or thereabouts" whereas wait() is a far more complicated beast, that involves both notifications and lock acquiring in addition to a timeout.
What is the meaning of wait(0)? Can't understand argument 0.
That means: Wait until that notify() comes in. Wait forever if you have to.
Thread.sleep(0) is simple: That does nothing (wait 0 milliseconds - okay, done. That was easy). Remember, the primary purpose of wait() is to wait for some other thread to run the code x.notify(), where x is the the same object you called wait() on, and the timeout is an afterthought. 0 means: No timeout, and is the default behaviour (there is a wait() method too, which is just wait(0)).
It can be any amount of time less than 'timeout' milliseconds.

while loop or Thread.sleep()?

I'm programming a game in Java and I limit the FPS to 60. I figured out 2 different ways to get the same result, but I'm wondering which of them is the better/cleaner way to do it. Or maybe you have a different idea.
while(System.nanoTime() - thisFrame < fps_limit);
or
Thread.sleep(sleepingTime);
My thinking is that the while loop effects the CPU more than Thread.sleep, am I right?
Thanks in advance for your help!
Dom
You have the following main options:
While loop - This will consume CPU cycles and often will actually stop the system because while you are looping, other threads cannot run (on a one-core machine).
Thread.sleep() - This can be effective but you need to remember that is not guaranteed to wait the specified time.
DelayQueue - More up-to-date. Better/accurate timing.
ScheduledThreadPoolExecutor - Still more up-to-date than DelayQueue. Uses a Thread Pool.
You're right, while both with achieve what you're trying to do, the while loop will keep the processor occupied, consuming CPU time.
In contrast, Thread.sleep() frees the processor for the amount of time mentioned.
So, Thread.sleep() is better.
Both the answers posted already are good - sleep is better than loop. However, you can go into much more detail about how to write a good loop. If you are interested, here is a great resource: http://www.java-gaming.org/index.php?topic=24220.0
It covers topics like variable timestep and interpolation, which can be used to make your graphics run extremely smoothly. This solves the issues Thread.sleep has with not being 100% accurate in its timing as well as preventing your graphics from appearing jerky if your game performs some calculation that takes some time.
What I would do (pseudo code).
//timepast since last loop in ms
timepast = 0
fpslimit = 60
finished = true;
//while the game is running
while(runnning)
{
timepast += timeSinceLastrun
if(timepast > 1second/fpslimit && finished)
{
finished = false
dostuff(timepast)
}
//sleep for the time of 1second/fpslimit - timepassed to avoid cpu blocking
Thread.sleep((1second/fpslimit) - timepast )
}
dostuff(deltatime)
{
//do stuff in the end after it finished set
//finished to true so dostuff can be called again
finished = true
timepast=0
}
In this way you can easily limit the fps with a variable and dont need to block other threads.
as OldCurmudgeon said thread.sleep dosnt block other threads in java and make processor time available.
Thread.sleep causes the current thread to suspend execution for a
specified period. This is an efficient means of making processor time
available to the other threads of an application or other applications
that might be running on a computer system
Also you can pass timepast to the dostuff method as a deltatime so the game runs the same on all devices (same speed).
I concur with #ayush - while loops are usually blocking functions, whereas threads are more like interrupt-driven or parallel programming functions. I'm a bit green on Java, but could you not setup a timer rather than sleeping?
Yeah it looks like Timer constructs, like in C++, are available. Check this out: Timer in Java Thread
You should use neither of them. Please take a look at the documentation for ScheduledThreadPoolExecutor
In particular you are looking at this function
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
while loop will use CPU resource and it is good only if your avg.waiting time is very less and expecting precision.
Thread.sleep() is fine if no precision is expected as CPU priority will change after thread wakes up and it may or may not be scheduled immediately to run and it also should not to be used like this
while(! canContinue()) {
Thread.sleep(1000);
}
For the above case, alternative is these cases better to use wait()/notify() if you want to suspend the current thread and wait for another thread to process something and then notify the current thread to continue.
some references you can read,
http://tutorials.jenkov.com/java-concurrency/thread-signaling.html
http://www.jsresources.org/faq_performance.html#thread_sleep

Repeat something after a specific time interval

I have been going through some of the SO questions about doing something after a specific interval of time (like printing hello world every five seconds).
I saw different ways that we can do it in a java program. my question is how java does this internally.
Once we run a java program, the main function starts executing in a thread. But this thread can be sent to Runnable state anytime(pause the execution). So if I had stated the print statement in the main function, how does java keep track of time now. what if the java program was not resumed for the next five seconds?
One way this could work is if we meant "every 5 seconds in the time period which the java program is running" . Is that how the JVM does this?
Assume that I have a single processor.
Ok, lets trace the calls. If we are using ScheduledThreadPoolExecutor we can find that it uses DelayedWorkQueue internally:
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
To await next tasks DelayedWorkQueue uses Condition available = lock.newCondition():
available.awaitNanos(delay);
Ok, lets take a look at awaitNanos implementation in AbstractQueuedSynchronizer:
LockSupport.parkNanos(this, nanosTimeout);
And the LockSUpport:
unsafe.park(false, nanos);
This is native method which uses operating systems's scheduler to delay thread execution.

Thread.sleep behaving weirdly

I have the following code:
public Move chooseMove(Board board) {
// start parallel thread
this.tn = new TreeNode(this.myboard, this, null);
tn.stop = false;
this.curT = (new Thread(tn));
this.curT.start();
try {
long startTime = System.currentTimeMillis();
Thread.sleep(4000 );
System.out.println(System.currentTimeMillis() - startTime);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
tn.stop=true;
return getBestMove();
}
}
The output is sometimes a value that is way greater than 4000ms like 5400ms which means that the thread is sleeping more than it should. Any help?
Thanks.
EDIT:
I understand that there is NO guarantee of Thread#sleep stoping precisely after the specified delay. However, an additional 1400ms is a long delay. Basically,I am implementing a game player agent and I need a way to run a task and then return a value to the server after 5s (or else the server ends the game). The server is using java.util.Timer.schedule(TimerTask task, long delay). There is only one thread running concurent to the main thread which is this.curT in the code above, so there is ins't really heavy multithreading.
From docs.oracle.com:
Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.
This is common behavior and it is described in Thread#sleep javadoc:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Based on this, there's no guarantee of Thread#sleep stoping the work of the thread by the amount of milliseconds stated in the parameter.
Thread#sleep will make your thread sleep for exactly 4 seconds and then wake up.
Once your thread has woken up the OS scheduler places it in the runnable queue.
When it is next picked by the scheduler it will become a running thread i.e. will occupy the CPU.
So there is an additional delay overhead due to the OS scheduler which can vary per OS, system load etc. This is unrelated to Java

How to get threads with loops running concurrently to work with Thread.yield()?

I have the following situation. I have an application that runs mostly on one thread. It has grown large, so I would like to run a watchdog thread that gets called whenever the main thread changes into a different block of code / method / class so I can see there is "movement" in the code. If the watchdog gets called by the same area for more than a second or a few, it shall set a volatile boolean that the main thread reads at the next checkpoint and terminate / restart.
Now the problem is getting either of the threads to run somewhat at the same time. As soon as the main thread is running, it will not let the watchdog timer count properly. I was therefore thinking of yielding every time it calls the watchdog (so it could calculate time passed and set the value) but to no avail. Using Thread.sleep(1) instead of Thread.yield() works. But I don't want to have several areas of code just wasting calculation time, I am sure I am not doing it the way it is meant to be used.
Here a very simple example of how I would use Thread.yield(). I do not understand why the Threads here will not switch (they do, after a "long" and largely unpredictable time). Please give me an advice on how to make this simple example output ONE and TWO after each other. Like written before, if I switch yield() with sleep(1), it will work just like I'd need it to (in spite of waiting senselessly).
Runnable run1 = new Runnable(){
public void run(){
while(true){
System.out.println("ONE");
Thread.yield();
}
}
};
Runnable run2 = new Runnable(){
public void run(){
while(true){
System.out.println("TWO");
Thread.yield();
}
}
};
Thread tr1 = new Thread(run1);
Thread tr2 = new Thread(run2);
tr1.start();
tr2.start();
Thread.yield()
This static method is essentially used to notify the system that the
current thread is willing to "give up the CPU" for a while. The
general idea is that:
The thread scheduler will select a different thread to run instead of
the current one.
However, the details of how yielding is implemented by the thread
scheduler differ from platform to platform. In general, you shouldn't
rely on it behaving in a particular way. Things that differ include:
when, after yielding, the thread will get an opportunity to run again;
whether or not the thread foregoes its remaining quantum.
The take away is this behavior is pretty much optional and not guaranteed to actually do anything deterministically.
What you are trying to do is serialize the output of two threads in your example and synchronize the output in your stated problem ( which is a different problem ), and that will require some sort of lock or mutex to block the second thread until the first thread is done, which kind of defeats the point of concurrency which is usually the reason threads are used.
Solution
What you really want is a shared piece of data for a flag status that the second thread can react to the first thread changing. Preferably and event driven message passing pattern would be even easier to implement in a concurrently safe manner.
The second thread would be spawned by the first thread and a method called on it to increment the counter for which block it is in, you would just use pure message passing and pass in a state flag Enum or some other notification of a state change.
What you don't want to do is do any kind of polling. Make it event driven and just have the second thread running always and checking the state of its instance variable that gets set by the parent thread.
I do not understand why the Threads here will not switch (they do, after a "long" and largely unpredictable time). Please give me an advice on how to make this simple example output ONE and TWO after each other. Like written before, if I switch yield() with sleep(1), it will work just like I'd need it to (in spite of waiting senselessly).
I think this is more about the difference between ~1000 println calls in a second (when you use sleep(1)) and many, many more without the sleep. I think the Thread is actually yielding but it may be that it is on a multiple processor box so the yield is effectively a no-op.
So what you are seeing is purely a race condition high volume blast to System.out. If you ran this for a minute with the results going to a file I think you'd see a similar number of "ONE" and "TWO" messages in the output. Even if you removed the yield() you would see this behavior.
I just ran a quick trial with your code sending the output to /tmp/x. The program with yield() ran for 5 seconds, generated 1.9m/483k lines, with the output sort | uniq -c of:
243152 ONE
240409 TWO
This means that each thread is generating upwards of 40,000 lines/second. Then I removed the yield() statements and I got just about the same results with different counts of lines like you'd expect with the race conditions -- but the same order of magnitude.

Categories