Alternative to Thread.sleep() function

Dear Experts,
I am developing an application that requires sleep times on the order of nanoseconds. I tried using the Thread.sleep(long milliseconds, int nanoseconds) function, but I found that the smallest time the function will sleep for is 1 millisecond (i.e sleep(1,0) sleeps for the same amount of time as sleep(0,1)). I am pretty sure that the smallest increment you can set a timer to is one millisecond as well. Are there functions out there that can output nanosecond delays?
Thanks

I am developing an application that requires sleep
ep times on the order of nanosecondsThread.sleep() gives you whatever the OS exposes. If the OS doesn't support sub-millisecond sleep times, then you won't get it.
More importantly, Thread.sleep() does not guarantee sleep times. If the OS scheduler decides that there are a dozen other processes with higher priority (or a dozen other threads in your process), you may find that you've slept for many milliseconds, maybe even seconds.
If you want more info, I recall www.javaworld.com having an article on sub-millisecond timing. You might want to check there to see if they say anything about sleep times.

Similar Messages

  • Replace the wait with java embedding thread.sleep() function

    Hi,
    How to replace the wait with java embedding thread.sleep() function. Can anyone help.
    Thanks.

    drag and drop the java embedding component
    include the following code in it.
    try{ 
    Thread.sleep(60000);
    }catch(Exception e)
    --Prasanna                                                                                                                                                                                                                                                                                                                           

  • Alternative to Thread.Sleep in catch?

    Is there any other way to make the code wait than using Thread.Sleep in catch, because Thread.Sleep disturbs other objects on my form. Here is what I'm trying to do:
    Try{
    //do something
    catch
    // wait 10 seconds
    //retry

    Timers are a bit of a nuisance what with keeping your form in memory even when you try and dispose the things.
    You could push the thing you're doing onto another thread.
    Use async await.
    You could then use Task.Delay.
    A very simplified example:
    private async void Button_Click1(object sender, RoutedEventArgs e)
    await Task.Delay(2000);
    // Do something
    Because that's an async method processing returns to the caller when it hits the await.
    That then pauses 2 seconds without impinging on your UI thread.
    Before the separate thread continues with the code after your await.
    You could put your try catch into a method like that and it'd do what you want without a timer.
    10 seconds seems a bit of a short time by the way.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • What is an alternate to Thread.Sleep()?

    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?

    watwatacrazy wrote:
    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?I am in no way condoning this idea, because as mentioned it is a very bad idea.
    However. Not lettiing you throw exceptions is not a reason to not do something. All it means is that you need a catch block. You should review the exceptions part of the Java tutorial found here [_Java Tutorial : Exceptions_|http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]

  • 10 ms overhead when calling Thread.sleep on Linux

    Hi,
    I have been working on a traffic shaping simulation that requires me to send packets on a ms basis. When I call Thread.sleep(11) on Linux 2.4, I get a constant return around 30 ms. I tried to bypass the Thread.sleep function and called directly the select() function under linux with a timeout of 11 ms then I get a constant return around 20 ms. Then if I create a test.c program that loop 100 times calling the select(11), I get a very accurate rate around 10-11 ms. Anyone knows where that 10 ms overhead comes from? I tried executing the java program with Thread.sleep and the -XX:ForceTimeHighResolution but it doesn;t seem to change anything ! Any info would be very welcome ! Thanks

    Actually I get this behavior only on a machine with kernel 2.4. On a different machine with kernel 2.6 I get an accuracy of 10ms for a select call with 10 ms timeout. I know there was some improvements on the jiffy for kernel2.6 but I still don't get why calling select timeout 10ms from a C program return an accuracy of 10ms on linux 2.4 and the same select() timeout 10ms called from java return an accuracy of only 20 ms on kernel 2.4..... :( still looking

  • Database queries - is there a wait or sleep functionality?

    Hello everyone,
    I have recently encountered a problem where a database collector I made
    just stops querying after a while and needs restarting in the ESM for it
    to work again. In other databases (I am querying Oracle btw), this does
    not happen and in some others it does. So I am basically thinking that
    some databases are configured to limit the amount of querying or force
    an exit on error.
    What I have noticed, is that in my Oracle environment (no fancy
    configurations, all very permissive) I get alot of ORA-0100 errors
    indicating that there are too many open cursors. This happens when the
    last row in the database has been reached and the errors stop being
    shown in Active Views only after some data is inserted in database and
    collector resumes normally the task of collecting data until no more
    records are available and once more errors appear in Active Views.
    I altered the amount of allowed open cursors and incremented from 300
    to 500. Still, I keep getting errors (like every 20 seconds). I want to
    minimize these amount of errors and hopefully solve my original problem
    of having to manually restart the collector in some customer
    environments. I came up with the following snippet (bottom of message),
    but can't seem to find a function for having the collector sleep or
    wait. I tried Thread.sleep() (From Java) and setTimeout() (From
    Javascript) but both raise errors since they are undefined methods for
    the collector.
    The Sentinel API makes reference to "queryDelay" and "queryScheduled"
    flags which are supposedly defined in sqlquery.js. I cannot find any
    reference in the code to these flags and I am not even sure of how to
    implement them ( if(!queryDelay) { conn.send(DBQUERY) } ?????? ).
    How can I use these flags in the code to help me reduce the number of
    queries being thrown when there is no data? Or will I have to hack my
    own sleep or wait function? I appreciate any assistance!
    snippet of code I want to implement:
    Code:
    Connector.prototype.sendQuery = function(){
    if (rec.CONNECTION_STATUS == "NEED-QUERY") {
    if (instance.CONFIG.myCounter >= 3) {
    //HERE INSERT A SLEEP OR TIMEOUT FUNCTION
    instance.CONFIG.myCounter = 0;
    } else {
    conn.send(instance.CONFIG.DBQuery);
    //instanced in initialization function. Resets to zero when query is successful.
    instance.CONFIG.myCounter = instance.CONFIG.myCounter + 1;
    return true
    Jean-Paul_GM
    Jean-Paul_GM's Profile: http://forums.novell.com/member.php?userid=12809
    View this thread: http://forums.novell.com/showthread.php?t=445597

    I experience the same problem with my custom collector.
    But the beta connector is not there anymore.
    Can you please provide the connector so that I can test if it solves my
    problem.
    Thanks.
    ab;2141610 Wrote:
    > -----BEGIN PGP SIGNED MESSAGE-----
    > Hash: SHA1
    >
    > If this works I'd like you to open an SR for it so we can link it to
    > the
    > bug, but in the meantime:
    >
    > 508a0b25988c98a152ff5889edb41882 jdbc2011.1r1beta2.tar.gz
    >
    > ftp://ftp.novell.com/outgoing/jdbc2011.1r1beta2.tar.gz
    >
    > This is a beta and has not been fully ZA'd but seems to resolve your
    > issue for another customer. If it does please be sure to at least
    > post
    > back here if not open an SR (which will be credited to you as this is
    > Bug# 700669 most likely).
    >
    > Good luck.
    >
    > - --
    > Want to yell at me in person?
    > Come to BrainShare 2011 in October: http://tinyurl.com/brainshare2011
    > -----BEGIN PGP SIGNATURE-----
    > Version: GnuPG v2.0.15 (GNU/Linux)
    > Comment: Using GnuPG with Mozilla - 'Enigmail: A simple interface for
    > OpenPGP email security' (http://enigmail.mozdev.org/)
    >
    > iQIcBAEBAgAGBQJOge8eAAoJEF+XTK08PnB5ORoQAJcX9moFMh AfcpLSaIVhFLFj
    > ZcmfRjJs4IyT+xatk9wp1S/+eq81AMuyxsoGK/RQfwkKQtzJWiUtQAulCVPjFJZP
    > 3Hy2yBAJYUe5Rm3kedfeFlW3vFIV7wecl4el1UPRs4Q9DBUuBa XqP1KHgDrx4iue
    > ECEph0scQmlp+SxeBUZKfVwWY9NRKio3kxRPJ3QmzPPQ8euP6Z RYcDtwfJq4rrQf
    > z8GcV4ylHZxgIqGXI2pV47zBPPuU/lppytAnyaZSQm5ODs1ndi8f7i/MLPZ4SGI4
    > rkjUURVmkYim7UOA6QLxYUxUJF5SDGyjyJS2h2wGb5caBACMsA XDeySZ6ARMxtqs
    > 9mzb+Zj3VC4+54yVFAXDUq7mzMa5NE0WqxTR9lNoBMnnLmjwyk b9YDfmDUFZCpmT
    > QtWM68bgqtl/p1kcjQq0yAsTVTniGsOynpfTvZjsi4Y4hDCC9ktf8HP7aqu+Tb Nn
    > ehVYbG8zM8muUfiAEMTfjm7X07DK5uTTduNnnCbysnvNcCdRlu SEinfZsDRiihEt
    > gdoYFRYicy3SrJTL769TlzlKd3LU8ICqy8fnHLVeJjPanWxRCQ ISFUuhb5NI1h8Q
    > unVZAzHzcpJCidMLm/cOpCVbyPeaTeG3HbQzNOqwKyd4FFfHvzIBh0JVzO2uCScf
    > nvoosfhMydAkj0sgWXvH
    > =AVMR
    > -----END PGP SIGNATURE-----
    hkalyoncu
    hkalyoncu's Profile: http://forums.novell.com/member.php?userid=63527
    View this thread: http://forums.novell.com/showthread.php?t=445597

  • Need help in using sleep function in pl/sql

    Hi,
    need help:
    I have a condition where i want to validate total_pass=total_fail and
    I want to use the sleep function in a pl/sql where i want to wait for 2 minutes ie.checking
    whether total_pass=total_fail based upon class_id .
    I have the data in the table as:
    CLASS_ID TOT_PASS TOT_FAIL
    1 10 10
    2 5 4
    3 6 6
    4 7 5
    Any help will be needful for me

    I'm not quite sure what you are lookg for here, but whatever it is, your code as posted won't do it. You will never break out of the WHILE r_Class.Tot_Pass = r_Class.Tot_Fail loop, since these values will never change because you never get the next record form the cursor.
    From your original data, it looks like your cursor will return multiple rows which implies to me that you want to fetch the first row from the cursor, check if tot_pass = tot_fail, if they are equal, sleep for two minutes then get the next row. This does not make sense to me. Once the select in the cursor is executed, the data it returns will not change due to Oracle's read consistency model, so there seems to me no point in the sleep.
    The other alternative I can see is that you want to check all the returned rows, and if tot_pass = tot_fail for one of the rows (or possibly for all of the rows), then you want to sleep and try again.
    If you can explain in words what it is you are trying to accomplish, someone will be able to point you to a solution.
    John

  • Sleep Function in PL/SQL

    Hi Guys,
    I am creating a procedure which will check for the fileld in the database and if it returns NULL should go to sleep for 15 minutes and then will again check for the field. I am planning to use DBMS_LOCK.SLEEP function. Please can you suggest if the same is fine or advise if in case there is any other specific function which I require to use as I have read that the mentioned function is not accurate in calculating the SLEEP time.
    [http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:6019886867656]
    Best Regards,
    Shaz

    Summary of DBMS_LOCK Subprograms
    Table 53-3 DBMS_LOCK Package Subprograms
    Subprogram Description
    ALLOCATE_UNIQUE Procedure
    Allocates a unique lock ID to a named lock.
    CONVERT Function
    Converts a lock from one mode to another.
    RELEASE Function
    Releases a lock.
    REQUEST Function
    Requests a lock of a specific mode.
    SLEEP Procedure
    Puts a procedure to sleep for a specific time.
    PL/SQL lock timer
    Definition: This Wait-Event represents the amount of time a user or application has “slept” through the USER_LOCK.SLEEP or DBMS_LOCK.SLEEP procedures.
    When investigating Oracle Wait-Events, the lion's share of time is spent looking at those events where applications consume precious system resources or are in direct contention with other users or applications. These resource waits revolve around excessive CPU, memory, or disk usage. Events that spin for Oracle internal structures such as latches or enqueues can also be of concern. As their name suggests, Wait-Events DO ‘wait’ on some event to complete before a user or application can continue with its work. Contention for system resources will overwhelm Oracle’s ability to immediately process the SQL and ultimately cause applications to accumulate time in resource specific Wait-Events.
    On the flip-side of resource waits there are what are called idle events. These events do not wait for any specific resource but record the time Oracle is waiting for a work request from the application. Many practitioners of Oracle performance will not even look at these idle events because they do not consume resources and are not limiting what Oracle can do at any given point in time. Some will even go so far as to state that the idle events have no meaningful information. This is not necessarily true. Take for instance the idle event ‘SQL*Net message from client’. This idle event is not inhibiting the database server from performing work but, as many agree, is an indication of poor response from client to database server. While idle events are not the result of direct resource contention, they are an accurate measure of accumulated delays in the application imposed by Oracle.
    The ‘idle’ event “PL/SQL lock timer” is worth watching because it points us in the direction of application response, throughput, and possible coding issues. The PL/SQL lock timer event is, as the command that issues it states, a sleep mandated by the application code. The application is idle and doing nothing. This means that if the application sleeps for a combined interval of 5 minutes, the response to the user or complete run of the application will take at least 5 minutes longer.
    While this event does not require resources and thus is not an Oracle resource contention issue, it is our job to provide the quickest response to users and push applications through our system to increase the user’s perceived performance.
    Most often, sleeps are put into an application for serialization of transactional events or spinning on queues until something happens. When the event occurs or a queue is populated, then the application continues its work. We should ask ourselves why an application is sleeping for any amount of time and provide alternatives if necessary to reduce this idle event. You will gain quicker responses if you trigger an action instead of the action waiting for an event.
    How to look at the PL/SQL lock timer event
    To initiate a sleep for the current session for five seconds.
    SQL> execute sys.dbms_lock.sleep(5);
    To take a look at current sessions that are using the SLEEP command. Notice that the column P1 in V$SESSION does not represent the amount of time the session has slept but in fact represents the duration this session will sleep. Also note that this column is in centiseconds and as such the five seconds issued for a sleep has been translated in to 500 centiseconds.
    SQL> select osuser,event,p1 from v$session where event = 'PL/SQL lock timer'
    OSUSER EVENT P1
    Johnny Smith PL/SQL lock timer 500

  • Can LabVIEW threads sleep in increments less than a millisecon​d?

    I am aware of two LabVIEW sleep functions:
    1) All Functions | Time & Dialog | "Wait (ms)"
    2) All Functions | Time & Dialog | "Wait Until Next ms Multiple"
    In this day and age, when 3GHz processors sell for less than $200, it seems to me that a millisecond is an eternity. Is there any way to tell your LabVIEW threads to sleep for something less than a millisecond?
    In Java, the standard Thread.sleep() method is written in milliseconds [sorry, the bulletin board software won't let me link directly]:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/​Thread.html#sleep(long)
    but there is a second version of the method that allows for the possiblity of nanoseconds:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/​Thread.html#sleep(long, int)
    So there does seem to be some consensus that millisecond sleep times are getting a little long in the tooth...

    Hi Tarheel !
    May be you should get some idea of the kind of timing accuracy that you can reach when using a loop.
    Use the attached vi, which runs repeatedly a For loop (10 iterations) reading the time, then calculate the average and standard deviation of the time difference between the loop iterations.
    On my PC (P4, 2.6 MHz, W2K), I get a standard deviation of about 8 ms, which appears to be independent of the sleep duration I asked for.
    Same thing with a timed loop.
    Under MacOS X (PowerBook, 1.5GHz), the SD falls down to 0.4 ms.
    I tried to disable most of the background processes running on my PC, but I could not get a better resolution.
    Seems that the issue is not in LV but on the way the OS manage its internal reference clock.
    Since you are a Java afficionado, may be you could produce something equivalent ?
    A proof that nanosecond resolution is available on a PC could be of great help to NI. Why bother with costly timers on DAQ cards ?
    By the way, it took me about one minute to create the attached vi. I would like to have an idea of the time required to do the same thing in Java.
    Tempus fugit...
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Timing precision.zip ‏11 KB

  • SLEEP FUNCTION QUESTION

    I have a Pearl 8130 (Verizon). 
    I am inquiring about the "sleep" function that happens when you buy a case with a magnet flipper.  Does it just dim the screen immediately?  Or does it do something else?  I'm curious because i bought a flipper case that I'm not pleased with and basically only wanted it for that function - does it REALLY save the battery?  Is it that necessary.  Thanks!
    Solved!
    Go to Solution.

    No it is not the same, as the sleeper magnet puts the BB to sleep in other ways, while in the holster. Dimming the backlight to 80% is a good battery saving tip as well, but is not the same as putting the BB to sleep in the holster.
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • Realtime equivalent to Java's Thread.sleep()?

    I have an application that I want to guarantee that when I call Java's Thread.sleep(n) the thread will sleep for precisely that amount of time, or close to it at least. What we recently encountered though was that if the "wall clock" time is changed in one thread while a sleep is occurring in another thread, this clock change will impact when the sleeping thread will wake up.
    In our case, we had a simple Thread.sleep(1000), and during that one second period another thread set the clock back two minutes. The sleeping thread ended up sleeping roughly two minutes and a second instead of just a second. Apparently this is a "feature" of Thread.sleep(), and I can see in some cases (e.g. a task scheduler based on wall clock times) where this is exactly the behavior you'd want. However, in our case, we want the sleep function to sleep by the amount we specify, regardless of changes to the wall clock time. Is there a way to do this in Java? We are using JDK 1.5.

    You can use methods which rely on the nanoTime() (based on the number of clock cycles since the processor last reset)
    Classes such as LockSupport.parkUntil(someObject, nanoTime) may give you the accuracy/consistency you want. In this case you always wait the full delay.(and not unpack it)

  • Since I installed Lion on my macbook the LED light does not pulse when I close the screen - the sleep function does not work.

    Since I installed Lion on my macbook the LED light does not pulse when I close the screen - the sleep function does not work neither when chosen after pressing the button nor chosen in the apple menu..

    I have had the same problem but on another forum it was suggested that disabling internet sharing would solve this. This fix seems to work on my machine - why it works I do not understand

  • External FW/USB Western Digital, Seagate Disk Drives and 'Sleep' function

    As you are aware, most external disk drives be they FW or USB (and irrespective of the manufacturer, save for LaCie) have a 'sleep' function built into their Firmware. In the case of the Western Digital and Seagate Ext FW drives I have, this function cannot be disabled and this per both WD and Seagate.
    Unfortunately this is extremely annoying if using Photoshop and Bridge...it takes about ten seconds for each disk to spin up while the latter programs search the drives. (In Windows this can be enabled/disabled. Not so with the Mac O/S I have been told). Multiply this by six of the aforementioned drives and it can be quite time consuming.
    Is there an OS-X workaround for this?
    Thanks again,
    Lyman

    I always avoid vendor cases. Might want to look at an Oxford 912 etc, or better yet, why use Firewire when eSATA works so well?

  • What's wrong to put Thread.sleep in a session bean?

    i am working on a trading platform and i think there is a design flaw. The part i am working on is the Order Management module. When an order value object is published to a JMS topic and picked up by a MDB. The MDB, in turn, calls a session bean (could be stateless, I didn't check), OrderEngineBean. After this bean saves the order vo into database and broadcast the message to all involved parties, it suspends for 12 sec, using Thread.sleep, so other parities might have a chance to update the vo. If no update occurs, the order is considered expired and abandoned.
    It looks awkward to me to use a Thread.sleep in a session, but I haven't come out with a better idea to deal with the scenario like above.
    Anyone can help me out?
    Thanks a lot!
    Sway

    Setting the property "max-beans-in-free-pool" is not the answer to this issue. By setting this property to 1, the container merely instantiates and keeps one instance of the bean in the free pool at the "start" of the app server. But if the container comes across more than one requests for the same EJB simultaneoulsy, then it will create new instances at that time to handle the requests simultaneously.
    You are seeing intermixed log messages between two threads because these messages are being logged from two different instances of the EJB and NOT the same instance of the EJB. The container does synchronizes the calls on "a method" on "a instance". So what you are seeing are the messages coming from "a method" on "two different instances" of the same EJB.
    You can refer to the EJB 2.0 specification section 6.11.6 Non-reentrant instances for details about simultaneous access to the same session object.

  • I can't use the sleep functions, is it a bug?

    i just updated my Ipod to 1.2 .And i found the sleep function is not available. there is no menu to set the sleep time. when i put the sleep menu , my nano turns off immediately. is it a software bug?

    i have had the answer.
    the sleep function can't be used as a sleep timer.the sleep timer is set in clock menu.

Maybe you are looking for

  • Burning a movie help please

    Hi everyone I have an Imac and am trying to burn a dvd that is an .avi file. so when I go into IDVD I drag the file to the drop zone that it shows me and then when I hit burn dvd it tells me that my project is too large to fit on the DVD. These are m

  • All possible combinations of 23 columns in a table.

    Hi, We have a table as follows; CREATE TABLE ALL_PROD_COMB_TMP HDLM_ID NUMBER(10), MULTIPATH_ID NUMBER(10), TRUE_COPY_ID NUMBER(10), UVM_ID NUMBER(10), TUNING_ID NUMBER(10), CLUSTER_ID NUMBER(10), MIDDLEWARE_ID NUMBER(10), TAPE_ID NUMBER(10), THIRD_P

  • AQ-Header parameters/ IP_MESSAGE_TYPE parameters

    Hi I am using AQ for BPEL-B2B communication I know we have some parameters of AQ header and IP_MESSAGE-TYPE but I am not sure how to populate, from where I have to get the values for these parameters and which are mandatory AQ-HEADER ========== PRIOR

  • Using Wolfram Alpha with Dragon Dictate

    I know that wolfram alpha has an api to use.  Would it be possible to use dragon dictate to ask your computer questions and use WA as the database?

  • I recently upgraded to snow leopard and now every time i open iCal i get multiple events to update in iCal

    I recently upgraded to snow leopard and now every time i open iCal i get multiple events to update in iCal.  Except I don't know where these are coming from or why.   I've check iCal preferences and Help - can't find a way to stop this from happening