Java - alternative to thread.sleep

I have a requirement to pause a while loop for a specific number of milliseconds. I have tried using Thread.sleep(duration) but it is not accurate, especially in a looping scenario. Millisecond accuracy is important in my program.

Here is the algorithm where I don't want to go back to check for condition until expectedElapsedTime has passed by.

while (condition) { time = System.currentTimeMillis(); //do something if (elapsedTime(time) < expectedElapsedTime) ) { pause the loop // NEED SUBSTITUTE FOR Thread.sleep() } // Alternative that I have tried but not giving good results is while ((elapsedTime(time) < expectedElapsedTime)) { //do nothing } } long elapsedTime(long time) { long diff = System.currentTimeMillis() - time; return diff; }

-------------Problems Reply------------

What do you expect?

If you go to sleep then once your process is again runable it will have to wait for the thread scheduler to schedule it again.

I mean if you go to sleep for 50 seconds that does not mean that your process will be running in exactly 50 seconds.Because ater it wakes and is runnable it will have to wait to be scheduled to CPU which takes extra time plus the time you have for context switch.

There is nothing you can do to control it so you can not have the accuracy you are saying.

For your case I would suggest a spinning loop instead.

long now = System.currentMillisec();
while(now < expectedElapsedTime){
now = System.currentMillisec();
}

Try a ScheduledThreadPoolExecutor. Its supposed to give more reliable timing results.

Java is not a real-time system, you can not make a thread go away and come back on such a tight schedule. To schedule your program execution down to millisecond you need to use a different platform - like simpleRTJ or Java Real-Time extension.

You could implement wait/notify mechanism and delegate to another thread the responsibility of notify the other thread in wait state that the amount of time is passed and that it can go ahead ...

For example when the threadA need to wait for a certain amount of time you can put the thread in wait state and start a timer task that after a certain amount of time (interval ) call notify and wake up the ThreadA that go ahead, this could be an alternative .

The delay is likely to arbitrarily chosen, so I would question your need to real time interval timing.

If you need read time you need to busy wait for the time to reached. Giving up the CPU means you can't guarantee you will get it back exactly when you want.

If you want to be accurate with sounds you use a sequencer and set the tempo in BPM: sequencer.setTempoInBPM(120);

Don't forget about garbage collector pauses. It can beat all your plans

The solution is to use a handler with a runnable and use of the method 'postDelayed'. Example:

new Handler().postDelayed(new Runnable() {
public void run () {
// Do delayed stuff!
}
}, 5000L); //5 seconds delay

http://stackoverflow.com/a/21680858

Category:java Views:0 Time:2012-02-04

Related post

  • Alternative to threads for implementing massive parallel calculation engine in c# or java? 2012-04-29

    Suppose there is a need for building a spreadsheet-like engine that needs to be ultra fast, each cell dependencies could be on parallel calculation branch. Could thread be created for each parallel branch ? Isn't thread costfull in term of memory. Ea

  • Alternative to thread for small tasks without freezing the GUI 2011-01-25

    I'm writing a small application, composed by a gui and a couple of buttons. When the user clicks one of them, the program must download a webpage, do a couple of matching and return a value to the gui. The question is, I must start a new thread every

  • Is java.util.Hashtable thread safe? 2011-09-13

    It's been a while since I've used hashtable for anything significant, but I seem to recall the get() and put() methods being synchronized. The JavaDocs don't reflect this. They simply say that the class Hashtable is synchronized. What can I assume? I

  • Java alternative to Windows Workflow Foundation 2009-04-17

    What Java alternatives are there to Windows Workflow Foundation? I am looking for something that provides at least the same features that WWF does, and has the same flexibility and relative ease of use. I would very much prefer a free solution. -----

  • Which Java APIs create Threads 2010-01-06

    Without having the source code for a Java API, is there anyway to know if the API methods create multiple threads ? Are there any conventions to follow if you are writing Java APIs and they create multiple threads. This may be very fundamental questi

  • Alternative to Threads 2010-02-05

    I've read that threads are very problematic. What alternatives are available? Something that handles blocking and stuff automatically? A lot of people recommend the background worker, but I've no idea why. Anyone care to explain "easy" alternatives?

  • Java RMI and Thread Synchronization questions 2010-02-16

    I actually have two questions about Java RMI and thread synchronization: 1) If I implement my RMI remote methods as synchronized, are they guaranteed to be mutually exclusive? I need to make sure that no two of my RMI methods (methods offered to clie

  • Understanding java's native threads and the jvm 2010-04-16

    I understand that the jvm is itself an application that turns the bytecode of the java executable into native machine code, but when using native threads I have some questions that I just cannot seem to answer. Does every thread create their own inst

  • Is there a java alternative to the Bayesian Belief Network Framework "Infer.NET"? 2010-10-14

    Is the are java alternative to Bayesian Belief Network framework - Infer.NET? Preferable if it be scalable(online learning for large datasets), well-supported(last updated since 2010) and open source and easy to write network structure. So all featur

  • Does java-me support threading? 2010-11-01

    does java-me support threading ? can you give me an example code that execute a function in another thread. --------------Solutions------------- Using Threads in J2ME Applications Example: public class DoAnotherThing extends Thread { public void run(

  • Is this Java encryption code thread safe? 2011-03-15

    I want to use the following code for a high-concurrency application where certain data must be encrypted and decrypted. So I need to know what part of this code should be synchronized, if any, to avoid unpredictable issues. public class DesEncrypter

  • Java kills daemon threads in applet reloads 2011-04-20

    I know that all daemon threads are supposed to be killed when no other non-daemon thread is alive. I am developping applet which gets data from static objects. Those static objects are downloading some data from remote server in daemon thread. Severa

  • Android: java.lang.OutOfMemoryError: thread creation failed 2011-07-17

    I recently uploaded my app on the android market and I am getting the following error that I cant trace it back: java.lang.OutOfMemoryError: thread creation failed at java.lang.VMThread.create(Native Method) at java.lang.Thread.start(Thread.java:1327

  • Pure Java alternative to JAI ImageIO for detecting CMYK images 2011-07-26

    first I'd like to explain the situation/requirements that lead to the question: In our web application we can't support CMYK images (JPEG) since IE 8 and below can't display them. Thus we need to detect when someone wants to upload such an image and

  • Java alternative for Ruby's vcr? 2011-10-16

    Is there a java alternative for Ruby's VCR? As far as I understand, the benefits of using VCR are immense, you can run an "integration test" and record the results, store them some where locally. Now from the next time when you need to run your tests

  • Java alternative for 'sort -V' 2012-02-16

    I'm looking for a pure-java alternative for the shell command: sort -V. I'm looking for a Comparator class that can simply be plugged in. The sort -V command simply sorts files with a version system (i.e. 3.2.0-11 is 10 bigger than 3.2.0-1, not .1 bi

  • Error in java when creating Threads 2012-04-29

    Error in java when creating Threads. The error is in "MainApp" with RandomCharacterThread being the error. The Thread t1 is expecting a char whereas i am giving it an int value. This is what had caused the error. I have added comments to make the cod

  • Java: Swing Libraries & Thread Safety 2008-10-08

    I've often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues: In what situations does the fact Swing is not thread safe come into play ? What sho

  • Java: alternative to sleep in loop? 2010-10-14

    I need to listen to a serial input continuously, but NetBeans warns "Invoking Thread.sleep in loop can cause performance problems." I understand why this causes performance problems, but what is the best alternative in Java? public class SerialIO ext

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.154 (s). 11 q(s)