Wait() vs sleep()

This is a purely general question, I was wondering which is better to use: sleep() or wait()?

Use sleep() if you just want to wait for some time,
for example if you want to wait before you retry to
create a socket connection when the first try failed.
This is wrong. Never use sleep when you are using synchronization, it could cause deadlocks. Instead, use wait as wait will release all your locks and thus reduce the chance of deadlock. Remember that your thread may be holding locks that you are unaware of so it's best to wait (not sleep).
Use wait() if you want to synchronize multiple
threads, for examplw when one thread has to wait for
the resutl of another thread. >
So fi you have only one thread ( and i assume that
have you never written a multithreaded app) just use
sleep() adn forget wait(). They might look similar but
serve quite different purposes.
Java is multithreaded by nature, it's impossible to write a non-multithreaded application in java as there are at least a few threads ( finalizer thread, GC thread, your main thread). And any non-trivial java program will have at least 2 threads. Any java application that uses swing has at least 7 threads. So you must expect that your code will be run in multiple threads and thus sleep is not a good choice.
I don't think that using sleep should be recomended because it doesn't release locks.

Similar Messages

  • Difference between wait() and sleep()

    hi
    can any one tell me what is the difference between wait() and sleep().
    thanks in advance.

    Mahaboob,
    This question has been asked before; however, I will give you a real life example.
    Imagine you are in a super market and you go to the till to pay by your card, then behind you there are 10 people waiting in queue. You card does not work since you have not supplied the right pin code; there are two option
    1- Sleep
    2- Wait
    1- If you sleep you will lock the till for your self and try to figure out the pin number while the queue behind you increase on the resource (till)
    so you are engaging the till and wasting its time and wasting the till machine resource (CPU)
    2- you are polite, you move aside and wait so so that others can use the resource (till) until somebody in the queue finishes ( a good person) and give you a shout to tell you come in to the till to process your payment; you wake up and enter the pin number and go out from the super market.
    Now when you sleep, the current thread locks the resource so no body can use it and wast the CPU time
    while wait make the current thread release the lock on the object and does not ( this thread) actually wast the CPU time
    There are much more explanantion, try to search this forum.
    Regards,
    Alan Mehio
    London,UK

  • Using wait or sleep without a thread

    Is there any method to do the equivalent of a wait or sleep without using threads?

    You have a single-threaded application executing, and
    you want to pause it at a given location for a given
    period of time. If you call sleep, you give up
    execution, which you don't want to do.What do you mean by not wanting to give "up execution"? It is the scheduler of your OS that decides when your program executes or not. Your code snippet does nothing but burn processor time (incidently pretending to the scheduler that it actually has something useful to do) which could be well used by some other process running on the computer. Use Thread.sleep instead, thats what it is there for. If you want to somehow affect the amount of processor time that the scheduler allocates to your process you will be better served by increasing its priority.
    having my skill and/or intelligence mocked Well, I have certainly not mocked your skill nor your intelligence, god knows that I have on occasion presented poor solutions in this and other forums, but lets not dwell on that...

  • Topic about wait(),join(),sleep() and yield()

    Hi there,
    I'm headache with the implementation of wait()��join()�� sleep() yield(). Can anybody tell me:
    1. what's the difference between wait() and join(), I can't see it.
    2. As I know if thread A waits on thread B then A will release the lock. How about join, or slepp, or yield?
    3. Why use notify()? As I see if thread A waits on thread B, when B completed without calling notify(), the A will continue its job!!
    thanks thanks thanks

    1. Object.wait() will make a thread wait until Object.notify() is called on the object. Thread.join() will make the running thread to wait until the thread object finish to execute.
    2. .wait() does not wait on thread, it wait on objects. .sleep(long timeout) is about the same as .wait(long timeout), except that it need to be awaken with a .interrupt, not .notify. Also you cannot awaken more than one thread with a .interrupt, while a call to .notifyAll() will awaken all threads waiting on that object. .yield() suspend the current thread only to give a chance to others thread to execute and the initial thread will continue ot execute only a hort time after the .yield().
    3. See #1, #2 and think a bit.
    Regards

  • 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

  • Loop on wait or sleep in oracle

    Hi all
    I had to check for a FILE1 on the Unix and then if the FILE1( we call it as Trigger file for the process) then it look for the Data file and theni i had to utl_file.fcopy.
    If the Trigger file is not there it has to look for file after 5 sec and this should continue for 5 times.
    Even the Trigger file is not found (some cases it is optional) then it should copy the the Data file.
    declare
    l_Trig_file   BOOLEAN := FALSE;
    l_Data_file  BOOLEAN := FALSE;
    File_Name  varchar2(30) :='Work_file';
    Input_Dir varchar2(30) :='INPUT_DIR';
    Work_Dir varchar2(30) :='WORK_DIR';
    begin
        IF NOT NVL(l_Trig_file   ,FALSE) THEN
       --here i had to wait for 5 seconds and also i had to loop for 5 times
          ELSIF NOT NVL(l_Data_file  ,FALSE) THEN
      dbms_output.put_line('data file not found');
          ELSE
             dbms_output.put_line( 'Copying the '||l_Data_file  ||'from source to destination' );
          UTL_FILE.fcopy (src_location    => Input_Dir ,
                                 src_filename    => l_Data_file  ,
                                dest_location   => Work_Dir,
                               dest_filename   => File_Name
          END IF;
          Please help how to make a procedure to wait for 5 sec and make it loop for 5 time...
    Thanks
    Rede

    Have a look at DBMS_LOCK.SLEEP procedure.

  • Wait or sleep?

    Hi,
    I am at University doing Java. My new assignment is multithreading in a Windows Application.
    So,
    I have created 2 threads (one with just a string and the other making a sound (wav file)).
    My problem now is ...
    I want the window to open first, then for the words to show up on the window, AND THEN the sound. Now I want the sound to be done in 3 consecutive times.
    In other words:
    1st: fT
    2nd: s1T
    3rd: s2T
    4th: s3T
    Basically here is what I did:
    import java.awt.*;
    import java.awt.event.*;
    public class WindowsAppli extends Frame {
        TextArea outArea = new TextArea("Incoming call ...\n");
         T1 firstT = new T1();
         T2 second1T = new T2();
        T2 second2T = new T2();
        T2 second3T = new T2();
            public WindowsAppli ()
           add(outArea);
           setLayout(new FlowLayout(FlowLayout.CENTER, 10, 15));
           Thread fT = new Thread(firstT);
           fT.start();
           try
              Thread.currentThread().sleep(10000);
           catch (InterruptedException e)
          outArea.append(firstT.res);
          Thread s1T = new Thread(second1T);
          Thread s2T = new Thread(second2T);
          Thread s3T = new Thread(second3T);
          s1T.start();
          s2T.start();
          s3T.start();
        public static void main(String[] args)
            Frame f = new WindowsAppli();
             f.setTitle("Windows Application");
              f.setSize(600,400);
              f.setVisible(true);
             f.addWindowListener (new WindowAdapter ()
                public void windowClosing(WindowEvent e)
                     System.exit(0);
    }Any help please?

    If you want to wait for some even to occur, use wait, and a corresponding notifyAll(), or the higher level scheduling tools in java.util.concurrent.
    If you want to pause for a fixed amount of time, use sleep, although if you're doing that in a loop, you may want java.util.Timer and TimerTask.

  • Difference betn  wait() and sleep() method of a thread

    Can anyone briefly differentiate between the sleep() and wait() method of a thread.

    [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#sleep(long)]sleep
    [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#wait()]wait

  • Servlets, Threads, sleep and wait

    Hi,
    I am new to servlet programming and have a problem.
    I want to create a servlet that is also Runnable. It should hold the HTTP request open, and then wait() or sleep(), waking up regularly to send data to the client.
    My code seems to work OK, and in the server logs I can see the debug messages where my servlet is sleeping and waking up. However, it doesn't keep the connection open. Instead, any clients that try to connect instantly receive an empty response.
    Can anyone explain why this is? I am a bit lost. Is the server (Tomcat) cutting my request off when I start to sleep or what?
    dave

    OK. Now seems like I have it working with sleep().
    I was doing something pretty dumb and assuming that a new HttpServlet instance was created for every request - doing things like this.request = request; - obviously this didn't work too wlell ;-)
    Now just using Thread.sleep() it works much better
    One more question - how can I get a separate servlet to call notify() on this servlet so that it wakes up and delivers its message? (I know I need to call wait() not sleep())
    Thanks
    dave

  • Sleep / wait function for Business Server Page

    Hi friends of BSP,
    on my BSP I generate at the onload function x iframes for calling BEx 7.x WebTemplates.
    It is a dynamical count of iframes depending on some URL parameters.
    Now, I get the problem, that if the count of iframes is to big, the system can not load all WebTemplates, because they are generated to fast and the system can not handle this amount of processes.
    Is there a possibility to include a wait or sleep function?
    If the answer is "yes", how to implement those functions?
    thanks for any help and support
    kind regards
    Patrick

    Hi Jamie,
    now, we us the JS method window.setTimeout().
    But there are some restrictions.
    In BSP Applications this method works only if the delayed functions is the same function calling the delayed function
    function delayFunction(index)
      var timeout
      timeout = window.setTimeout(function() { delayFunction(i) }, 1000);
    and the delayed called has to be the last step of the function
    (for exmaple there is no possibility to include the setTimeout-function in an IF condition or in any loop).
    Many thanks
    Kind regards
    Patrick

  • Sleep and hibernation is working on Server 2012 with started hypervisor! I do not know why...

    Hi,
    I enabled Hyper-V role in the Microsoft Windows Server 2012 on testing computer (PC with i7 CPU and 16GB RAM). I found very strange behavior. The sleep mode was enabled and after command “powercfg /hibernation on” the hibernation is also working.
    I tested sleep (S3) and hibernation with started hypervisor and with running virtual machine. I tested sleep and hibernation triggered by power button and even with time-out that was set in the Power Options (I set sleep after 1 minute and
    later hibernate after 1 minute and wait).
    Sleep and hibernation is working! I do not understand why. Sleep and hibernation should be functional only on Client Hyper-V on Windows 8 and not on the Server 2012.
    Some examples:
    Testing workstation (i7, 16GB RAM) with Server 2012 and with started hypervisor:
    C:\Users\Administrator>powercfg /a
    The following sleep states are available on this system:
        Standby (S3)
        Hibernate
        Fast Startup
    The following sleep states are not available on this system:
        Standby (S1)
            The system firmware does not support this standby state.
        Standby (S2)
            The system firmware does not support this standby state.
        Standby (Connected)
            The hypervisor does not support this standby state.
            The system firmware does not support this standby state.
        Hybrid Sleep
            The hypervisor does not support this standby state.
    My laptop (i5, 8GB RAM) with Server 2012 and with started hypervisor:
    >powercfg /a
    The following sleep states are not available on this system:
        Standby (S1)
            The system firmware does not support this standby state.
            An internal system component has disabled this standby state.
                    Hypervisor
        Standby (S2)
            The system firmware does not support this standby state.
            An internal system component has disabled this standby state.
                    Hypervisor
        Standby (S3)
            An internal system component has disabled this standby state.
                    Hypervisor
        Hibernate
            An internal system component has disabled hibernation.
                    Hypervisor
        Standby (Connected)
            The hypervisor does not support this standby state.
            The system firmware does not support this standby state.
        Hybrid Sleep
            Standby (S3) is not available.
            Hibernation is not available.
            The hypervisor does not support this standby state.
        Fast Startup
            Hibernation is not available.
    R. Revil
    Relef Revil

    Hi Ben,
    I have nearly exactly the same Problem as Relef Revil.
    I have Lenovo T510 Notebook with Core I7 and a Lenovo T420 Notebook with a CoreI5.
    On my T510 S3 Sleep works perfectly with Hyper-V Role. On my T420 Sleep is disabled due to Hypervisor.
    If I uninstall Hyper-V Role then Sleep works again as expected.
    So, from a Little simple perspective, I Looks like this is a Hyper-V Thing or Problem.
    I have als updated to the latest BIOS and latest Intel HD Graphics 3000 Drivers on this Win 2012R2 Maschine.
    Also I have installed all possbile latest Versions of all other devices.
    Could you probably give me an idea where to search for a solution.
    So, what is the logic why Hyper-V disables sleep, when Sleep worked before?
    I assumed that Hyper-V and Sleep ist generally possible on Win2012R2, especially when Sleep works perfectly when Hyper-V Role is not installed.
    Kind Regards
    Marcus
    C:\Users\Marcus.Koenig>powercfg /a
    The following sleep states are not available on this system:
    Standby (S1)
    The system firmware does not support this standby state.
    An internal system component has disabled this standby state.
    Hypervisor
    Standby (S2)
    The system firmware does not support this standby state.
    An internal system component has disabled this standby state.
    Hypervisor
    Standby (S3)
    An internal system component has disabled this standby state.
    Hypervisor
    Hibernate
    An internal system component has disabled hibernation.
    Hypervisor
    Standby (Connected)
    The hypervisor does not support this standby state.
    The system firmware does not support this standby state.
    Hybrid Sleep
    Standby (S3) is not available.
    Hibernation is not available.
    The hypervisor does not support this standby state.
    Fast Startup
    Hibernation is not available.
    C:\Users\Marcus.Koenig>

  • New MBP 2.93 tried to fry itself in sleep mode

    Just bought a new MBP on Friday.
    Put it in a case.
    Hour later, opened the case.
    Noticed a burnt electrical smell.
    Picked it up and about dropped it, it was so hot.
    Fans were wide open.
    Took about twenty minuets to cool off and start back up.
    Lucky for me, I interrupted it before it burst into flames and burned my house down.
    I now look at it with a wary eye.
    I took it back to the store and "maybe" they will replace it.
    We will see.
    I am a switcher.
    This was my first real Mac.
    I loved it for the first 24 hrs.
    Message was edited by: chazwood

    chazwood wrote:
    I thought when the lid was closed, the book went to sleep. This is not normal?
    Even if you are in the middle of a program and you close the lid...... it does not go to sleep?
    Yes, when you close the lid, it goes to sleep. But, to anthropomorphize a bit, when you lay down and close your eyes, do you fall asleep immediately after closing your eyes? Your MBP does not sleep immediately when you close the lid. The Safe Sleep process first writes the contents of the RAM to the HDD. The more RAM you have, the longer that takes (up to a minute). During this time, the light on the front is solid; after the write is completed, the light starts to 'pulsate'. If you close the lid, then grab your MBP and take off, you may activate the Sudden Motion Sensor, which parks the HDD heads. That interrupts the Safe Sleep process, with unpredictable results (but usually along the lines of the MBP waking itself up later with the lid still closed).
    So, are you waiting until you see the pulsing light before moving your MBP? Apple advises doing so. If you are already doing that, there is some other cause, Bluetooth, etc.
    Personally, I never shut down my MBP - I just close the lid, wait for sleep, then take it and go. Been doing that several times a day for over 3 years, and it's never woken up 'on its own'.
    chazwood wrote:
    WARNING: this notebook does not actually work like every other notebook you have ever had, or heard about.
    Well, that part's certainly true. It works better. In particular, I have often wondered why, while my Apple and work-issued Windows laptops all go to sleep when the lid is closed, on those Windows laptops I have to press a button to wake the thing up. If I open the computer, it's because I'm ready to compute, I don't want open the lid then press a button - I want to open the lid and start working. Why is that so hard for Windows to understand? Sigh. Just one more 'wall' to climb over...

  • Java thread sleeps forever

    i am using the following code the problem i am facing is that the thread does not return from sleep only in one condition.can any one guide me regarding this.
    can i know in what condition the java thread does not return after sleep.
    while(ivIsActive)
    // call some functions
    try
    Thread.currentThread().sleep(ivSleepTime * 1000);
    catch (InterruptedException iException)
    { //............     }

    wait (even with a timeout) and sleep really have
    rather different functions and I'd be disinclined to
    use wait where sleep was appropriate.If you ever what a sleep() to finish early use a wait().
    If you try to interrupt a sleep there is no guarentee that this will not interrrupt in an unexpected place. With wiat you can be sure only thread waiting on a given object will receive the notify.
    I almost never use sleep in preference for wait for this reason.
    I consider it unwise to place much dependence on a notify not occuring, A notify should occur when you execute it. If you don't call notify, it doesn't.
    you might use wait/notify on the object in question for some unrelated purpose
    in different threads, forgetting this sleep. The notify should signify that a change has occured. The code should then test what has changed and what it should do about it. If you use this approach there is little impact in using the same notify for different purposes. If this is of real concern and you can use a dedicated object for notifying a change in the isAlive state (and make it private)
    (I invariably use while tests before wait, rather than if tests).Could you clarify this point?
    I think wait(time) should be regarded as a semaphore wait with timeout.I agreee. An if you want a Thread.run() loop to exit in a timely fashion then wait() is the thing to use. If you it is a requirement that the loop exit after the 30 second, then use sleep();
    Anyway, as to the original problem I think you need
    to make 500% sure that ivSleepTIme is what you think
    it is (because I'd be extremely surprised if it is).
    This is probably a good place for an assertion.I would also check that isAlive is really changing. It is not uncommon to be changing the isAlive in another context, or another object, or not at all.

  • Aluminum PB Won't Automatically Sleep

    I posted this before, but said Titanium when I meant Aluminum. So I've posted again with the correction.
    My 15" Aluminum Powerbook won't automatically sleep any longer. This seems to coincide with my upgrade to 10.4.2, or perhaps the recent AirPort upgrade. (I'm not totally sure.)
    While the computer will not actually go to sleep automatically, the screen, however, will go black -- but the sleep light doesn't actually come on..
    To fix this, I have tried:
    1) Resetting P-RAM (command-option-P-R)
    2) Resetting Power Manager (battery out, AC power out, hold power button for 5 seconds)
    3) Disconnectting AC power and removing battery for 30 min. to reset computer internals.
    4) Repairing Permissions
    5) Booting up, don't start any apps, and waiting for sleep.
    No matter what I do, the computer will not automatically go to sleep.
    Any help appreciated.
    Best,
    Mark

    I've been having this problem for a while now; in fact, perhaps since after 10.4.2, I would reckon.
    This is quite an important thing, as I do a lot of work on site with my Powerbook, and it is very inconvinent when I run out of battery. However, bringing this up on these message boards can give people the impression that you just don't know what the "Energy Saver" function of System Preferences can do!
    Does anybody have any tips for identifying processes that run in the background? I've been looking at the terminal command top, but not really finding anything. It does tell me how many processes are running, however.

  • Simple Blocking and Waiting

    hello,
    I am studying concurrency, and was hoping some could confirm I have got this right so far...
    1) When a thread waits() or sleeps(...), or sits around for an acquire()..they are all the same in terms of the CPU cycles...ie. none, they are not busy waiting?
    2) Also, if I put a wait(time) at the start of a Critical Section, when the time expires, it will enter the subsequent Critical section regardless? I.e a notify would just mean it gets there sooner...
    thanks
    julian

    vijaykandy wrote:
    it makes no sense to put a wait(time) call in a while(condition) loop. either the condition will be met and the object notified, or the wait call will timeout, in which case you will just loop around and wait again. Maybe so. The poster who asked the question needed to understand wait(timeout)/notify() scenario hence the example.only, your example didn't actually help them understand why you would wait with a timeout, which is what i was pointing out. as dannyyates subsequently pointed out, in your example loop, the timeout was useless.
    not to mention that you don't usually notify before you enter the critical section. you notify when you are leaving the critical section. also, you would set notAvailable to true when you enter the critical section. in short, that example is completely broken.It's not broken. If you think it is, can you provide an explanation, a problem scenario? Please don't confuse readers with blanket statements.
    For any one interested - Java monitors are called "Signal and Continue" (search on google) because they can signal other threads and still continue to hold the lock. Besides, always remember that a.notify() must be called only when thread acquires a's lock; otherwise an exception is thrown. The problem in the example is not with the notify() but with where the condition is toggled. If there are threads that call methods on another class based on the condition (notAvailable), they might run into an exception condition because condition was toggled prematurely. Since the original question did not address this scenario, this example will suffice.thanks for the tutorial on wait/notify. but, i wasn't confused at how they worked, just at your example. actually, your explanation here is broken, because no other thread (assuming correct syncronization) would ever see the new value of notAvailable until the current thread exited the sync block. you are correct that it doesn't "technically" matter where the notify is located, however, there's no sense waking the other threads before you do the actual work, you're just wasting other thread resources. however, your followup example is more what i would expect in terms of normal sync handling, so i guess you get the general idea (other than the timeout).
    again, my point was that your original example was not necessarily useful for understanding how sync worked. you made a couple of followup posts which seem to indicate that you basically know how it all, which leads me to wonder why you didn't include all that knowledge in your original example.
    Edited by: jtahlborn on Apr 20, 2008 9:00 PM

Maybe you are looking for

  • Windows freezes when I plug in iPod

    My iPod was working fine until I updated my iTunes software yesterday (10.15.05). While updating my computer froze completely and I had to do a hard shut down. Now, when I plug in to the USB 2.0 port (which is Belkin pc card external - bought at an a

  • Why is my Bluetooth not available?

    Some time ago, for no apparent reason, my Bluetooth on my MacBook stopped working. I have the ICON in the menu bar but it has a lne through it and says it's not available. Can anyone help me trouble shoot this? Thanks in advance.

  • Dbms_awm Package

    Hello, in 10g Release 1 i can us the dbms_awm Package to create Analytic Workspaces. Can i create Analytic Workspaces in 10g Releas 2 on the same way?? Because in the OLAP Reference for this Release the Package where not named.

  • HP 2600n Not Printing Correctly and Lost Functions

    The 2600n has lost the following functions with the HP/Apple update based on my normal use. Note that all of these were functioning prior to update. 1. Double sided printing not selectable; no double sided printing available 2. Cannot print 2 pages o

  • Converting 2.5 reports to 6i

    Where can I find the info on how to convert character mode 2.5 reports to 6i version? null