Diffrence Between Notify & NotifyAll ?

Discussion in 'Java' started by vj, Dec 11, 2005.

  1. vj

    vj Guest

    Hello group,

    I know that its a very lame question to ask experts like you but still
    i cannot help myself asking the question that "What is the Diffrence
    Between Notify & NotifyAll" method in the Object Class.

    Well so far my search on the Internet and JDK Documentation reveals
    that 'notify' method wakes up a single thread waiting on the object
    and passes the control of the monitor to it. So far so good and for
    'NotifyAll' it says that its will wake up all the threads waiting on
    the object and will select a thread to pass control to it. Well as per
    me during that period the unselected thread will again go back to sleep
    in the JVM scheduler list and they will need yet another call to
    Notifty (or NotifyAll) in order to wake them up. So, as far as i see
    there is no diffrence between notify & notifyall as they both will
    result in waking up a single thread waiting on the Object.

    If above assertions are indeed true than why to have two diffrent
    methods.

    Thanks,

    VJ
     
    vj, Dec 11, 2005
    #1
    1. Advertising

  2. vj

    Fred Guest

    I think you answer your own question.

    notifyAll wakes up a larger candidate pool of threads - any of those
    threads that are notified are candidates to enter the 'running' state.
    notify wakes up only one thread, and this thread is the only candidate
    to enter the 'running' state.

    If you have more than one thread waiting on a monitor, it almost always
    makes sense to use 'notifyAll.'

    -Fred
     
    Fred, Dec 11, 2005
    #2
    1. Advertising

  3. vj

    vj Guest

    >>notifyAll wakes up a larger candidate pool of threads - any of those
    >>threads that are notified are candidates to enter the 'running' state.

    but only one thread can ever be active inside a synchronized block
    right. And then to
    only one thread will be selected tobe woken up and all other threads
    though waked up will be
    again put to sleep. So the question remains whats the diffrence.

    -vj
     
    vj, Dec 11, 2005
    #3
  4. vj

    Chris Smith Guest

    vj <> wrote:
    > >>notifyAll wakes up a larger candidate pool of threads - any of those
    > >>threads that are notified are candidates to enter the 'running' state.

    > but only one thread can ever be active inside a synchronized block
    > right. And then to
    > only one thread will be selected tobe woken up and all other threads
    > though waked up will be
    > again put to sleep. So the question remains whats the diffrence.


    The difference comes after that first thread leaves the synchronized
    block. If you've used notify, the remaining threads are still waiting,
    so they won't do anything until the next call to notify or notifyAll.
    If you've used notifyAll, then those threads are only blocked attempting
    to gain the lock. As soon as the first thread leaves the synchronized
    block, the next thread is capable of proceeeding without a second call
    to notify(All). And then the third thread, and the fourth, and so on.

    In practice, Object.wait should only be called within a loop inside of
    the synchronized block, so those threads will check the predicate
    condition again and possibly go back into the wait state. For that
    reason, notify() can be seen as an optimization of notifyAll(), which
    can only be used with there's a need for only one thread to proceed. If
    you call notifyAll when only one thread is needed, and assuming you've
    properly written a predicate loop, the remaining threads will wake up,
    but will then just check the predicate condition and find that the first
    thread made it true again, so they'll go back to waiting. Nevertheless,
    they do wake up and run some code.

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Dec 11, 2005
    #4
  5. Chris Smith wrote:
    > vj <> wrote:
    >
    >>>>notifyAll wakes up a larger candidate pool of threads - any of those
    >>>>threads that are notified are candidates to enter the 'running' state.


    notifyAll causes at most one Thread to move from Thread.State.WAITING to
    RUNNABLE (but not immediately, see below). The other waiters will move
    to BLOCKED. It is possible that the thread that acquires the lock and
    becomes runnable was actually blocked at the start of a synchronize
    block, rather than waiting in wait.

    >>but only one thread can ever be active inside a synchronized block
    >>right. And then to
    >>only one thread will be selected tobe woken up and all other threads
    >>though waked up will be
    >>again put to sleep. So the question remains whats the diffrence.

    >
    >
    > The difference comes after that first thread leaves the synchronized
    > block. If you've used notify, the remaining threads are still waiting,
    > so they won't do anything until the next call to notify or notifyAll.
    > If you've used notifyAll, then those threads are only blocked attempting
    > to gain the lock. As soon as the first thread leaves the synchronized
    > block, the next thread is capable of proceeeding without a second call
    > to notify(All). And then the third thread, and the fourth, and so on.


    One subtlety I think worth pointing out is that wait releases the lock
    (however many times), waits, and then reacquires the lock. notify and
    notifyAll are different in that they do not release the lock. You can
    put the notify at the top of the synchronize block. Indeed doing so
    allows better exception behaviour.

    Also note that threads can wake spuriously. So, notify could
    theoretically wake more than one thread. And make sure you have that
    while loop - I have found shipping, commercial software that did not.

    > In practice, Object.wait should only be called within a loop inside of
    > the synchronized block, so those threads will check the predicate
    > condition again and possibly go back into the wait state. For that
    > reason, notify() can be seen as an optimization of notifyAll(), which
    > can only be used with there's a need for only one thread to proceed. If
    > you call notifyAll when only one thread is needed, and assuming you've
    > properly written a predicate loop, the remaining threads will wake up,
    > but will then just check the predicate condition and find that the first
    > thread made it true again, so they'll go back to waiting. Nevertheless,
    > they do wake up and run some code.


    notify instead of notifyAll can give a huge performance improvement. I
    have found shipping, commercial software waking an entire waiting
    thread-pool of around three hundred threads for each work request.

    On the basis of saying what you mean, I prefer notify to notifyAll where
    it is applicable. You mean wake one thread, say wake one thread.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Dec 11, 2005
    #5
  6. vj

    Chris Uppal Guest

    Thomas Hawtin wrote:

    > notify instead of notifyAll can give a huge performance improvement. I
    > have found shipping, commercial software waking an entire waiting
    > thread-pool of around three hundred threads for each work request.
    >
    > On the basis of saying what you mean, I prefer notify to notifyAll where
    > it is applicable. You mean wake one thread, say wake one thread.


    But using notify() is a good deal harder to get right. Tracking /which/ thread
    needs to be notified is tricky what with race-conditions etc. I would
    recommend /against/ using notify() unless (as we always say) there is an
    actual, measurable, performance problem which has to be fixed. This is more
    than just the usual dislike of premature optimisation, since we are not just
    talking about the risk of wasting time on needless complexity, but the very
    real risk of writing code that will fail mysteriously and irreproducibly.

    /You/ may trust youself to get it right -- I don't suggest you shouldn't -- but
    I would worry if I saw notify() used in most code-bases.

    Anyway, with luck we shall soon all be able to forget that
    wait()/notify()/notifyAll() ever existed, and leave the hard work to Doug Lea
    and java.util.concurrency.*

    -- chris
     
    Chris Uppal, Dec 12, 2005
    #6
  7. vj

    Chris Smith Guest

    Chris Uppal <-THIS.org> wrote:
    > But using notify() is a good deal harder to get right. Tracking /which/ thread
    > needs to be notified is tricky what with race-conditions etc.


    In fact, clearly it is ALWAYS a bug to use notify() whenever there could
    be heterogenous threads waiting on a single monitor. Why? Because you
    can't specify which thread to notify; so if you care (that is, if the
    threads do different things) then you've done something wrong.

    > Anyway, with luck we shall soon all be able to forget that
    > wait()/notify()/notifyAll() ever existed, and leave the hard work to Doug Lea
    > and java.util.concurrency.*


    I'm rather skeptical about this. The new package certainly introduces
    tools for solving a few specific common concurrency problems, such as
    thread pools and the classic producer/consumer example. However, if I'm
    writing concurrent algorithms for matrix operations in a mathematical
    computing library, I don't think Doug's done much to help me out.

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Dec 12, 2005
    #7
  8. vj

    vj Guest

    >One subtlety I think worth pointing out is that wait releases the lock
    >(however many times), waits, and then reacquires the lock. notify and
    >notifyAll are different in that they do not release the lock. You can
    >put the notify at the top of the synchronize block. Indeed doing so
    >allows better exception behaviour.


    >Also note that threads can wake spuriously. So, notify could
    >theoretically wake more than one thread. And make sure you have that
    >while loop - I have found shipping, commercial software that did not.


    can you please make you point more clear by giving us a sample code
    listing.

    Thanks,

    ---VJ
     
    vj, Dec 12, 2005
    #8
  9. vj

    Chris Smith Guest

    vj <> wrote:
    > can you please make you point more clear by giving us a sample code
    > listing.


    Which statement of Thomas's did you want sample code for? Since they're
    statements about multithreading and its inherently nondeterministic
    nature, it would be tough to demonstrate either one with sample code.

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Dec 12, 2005
    #9
  10. vj

    Chris Smith Guest

    Thomas Hawtin <> wrote:
    > One subtlety I think worth pointing out is that wait releases the lock
    > (however many times), waits, and then reacquires the lock. notify and
    > notifyAll are different in that they do not release the lock.


    Neither notify nor notifyAll releases the lock, so I don't see how this
    is a difference. Indeed, if either one did release the monitor, it
    would be terribly broken behavior.

    > Also note that threads can wake spuriously. So, notify could
    > theoretically wake more than one thread.


    Indeed. Good point; the intent is for notify to wake only one thread,
    but it could wake more. This is consistent with seeing notify as an
    optimization of notifyAll, as mentioned earlier in the thread. If it's
    too expensive to prevent notify from acting just like notifyAll, then an
    implementation could do so and be entirely legal.

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Dec 12, 2005
    #10
  11. Chris Smith wrote:
    > Thomas Hawtin <> wrote:
    >
    >>One subtlety I think worth pointing out is that wait releases the lock
    >>(however many times), waits, and then reacquires the lock. notify and
    >>notifyAll are different in that they do not release the lock.

    >
    >
    > Neither notify nor notifyAll releases the lock, so I don't see how this
    > is a difference. [...]


    I believe Tom meant that there was a difference between wait() on the
    one hand and notify() / notifyAll() on the other. At least, that's the
    way I read it.

    --
    John Bollinger
     
    John C. Bollinger, Dec 13, 2005
    #11
  12. vj

    Chris Smith Guest

    John C. Bollinger <> wrote:
    > I believe Tom meant that there was a difference between wait() on the
    > one hand and notify() / notifyAll() on the other. At least, that's the
    > way I read it.


    Ah! That does solve some of the mystery. Of course, there are many,
    many differences between wait and notify/notifyAll, since they do
    entirely different -- close to opposite -- things. Still a little
    confused, but it's time to drop it...

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Dec 13, 2005
    #12
  13. vj

    vj Guest

    > Which statement of Thomas's did you want sample code for? Since they're
    > statements about multithreading and its inherently nondeterministic
    > nature, it would be tough to demonstrate either one with sample code.


    Thomas suggested that the wait() call must be encapsulated in a loop
    that checks for wakeup conditions. I am requesting a sample that shows
    its usage over wait() thats not called from a loop.
    --
    VJ
     
    vj, Dec 13, 2005
    #13
  14. vj

    Chris Smith Guest

    vj <> wrote:
    > Thomas suggested that the wait() call must be encapsulated in a loop
    > that checks for wakeup conditions. I am requesting a sample that shows
    > its usage over wait() thats not called from a loop.


    Very precisely, the program must be written so that it behaves correctly
    for a wait function that returns earlier the the next notify or
    notifyAll. To put it in simple terms, imagine that Object.wait() were
    implemented like this:

    public void wait() throws InterruptedException
    {
    magicallyReleaseLock();
    // don't really wait at all!
    magicallyReacquireLock();
    }

    Would your code still work, except for any performance requirements? If
    not, then your code is already broken.

    Practically speaking, this always involves writing a loop. Just for
    completeness sake, I'll point out that in theory you could actually use
    recursion instead... but it would be a heck of a complicated mess.

    I don't doubt that you saw broken sample code. Unfortunately, it
    happens rather frequently.

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Dec 13, 2005
    #14
  15. vj

    Chris Uppal Guest

    Chris Smith wrote:

    [me:]
    > > But using notify() is a good deal harder to get right. Tracking
    > > /which/ thread needs to be notified is tricky what with race-conditions
    > > etc.

    >
    > In fact, clearly it is ALWAYS a bug to use notify() whenever there could
    > be heterogenous threads waiting on a single monitor. Why? Because you
    > can't specify which thread to notify; so if you care (that is, if the
    > threads do different things) then you've done something wrong.


    This doesn't seem to make sense; am I missing your point, or did you mean
    notifyAll() can't be used in such a situation ?


    > > Anyway, with luck we shall soon all be able to forget that
    > > wait()/notify()/notifyAll() ever existed, and leave the hard work to
    > > Doug Lea and java.util.concurrency.*

    >
    > I'm rather skeptical about this. The new package certainly introduces
    > tools for solving a few specific common concurrency problems, such as
    > thread pools and the classic producer/consumer example. However, if I'm
    > writing concurrent algorithms for matrix operations in a mathematical
    > computing library, I don't think Doug's done much to help me out.


    Point taken. But I don't think that concurrent matrix operations are a primary
    use-case for less-than-highly skilled programmers. Come to that, I don't
    immediately see a lot of need for complex wait-dances in such cases either, not
    more than can be handled by the handshake primitives (Barrier, Latch,
    Semaphore) that are in there already. But then, I have never paid much
    attention to concurrent [array] algorithms, nor really used j.u.c.* yet, so I
    may be missing much.

    BTW, do you do a lot of concurrent number crunching at DesignACourse ? ;-)

    -- chris
     
    Chris Uppal, Dec 13, 2005
    #15
  16. vj wrote:
    >>Which statement of Thomas's did you want sample code for? Since they're
    >>statements about multithreading and its inherently nondeterministic
    >>nature, it would be tough to demonstrate either one with sample code.

    >
    >
    > Thomas suggested that the wait() call must be encapsulated in a loop
    > that checks for wakeup conditions. I am requesting a sample that shows
    > its usage over wait() thats not called from a loop.


    Open the src.zip in your JDK, if you have not already done so. Look at
    java.awt.EventQueue.invokeAndWait (not invokeLater).

    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4974934

    With the "clarification" in 1.5 this code, although it does work on
    Sun's JVM, is not safe in general. Unfortunately it is in a place where
    it seems likely people will look for an example. The reason it works,
    assuming no spurious wakeups, is related to the waiter lying in the
    synchronised block throughout the multi-threaded life-cycle (and that
    notifies do not release locks, making them different to how wait
    operates in this respect).


    I got an e-mail from the responsible engineer this morning. It will be
    fixed with a change to a public API (although I have demonstrated a fix
    without). Unfortunately it's too late for a public API change in that
    area for Mustang, so it'll be in 7.0 (due 2008, IIRC).

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
     
    Thomas Hawtin, Dec 13, 2005
    #16
  17. vj

    mallikk

    Joined:
    Oct 22, 2007
    Messages:
    2
    why notify() is sending notification to all waiting threads.

    Please do help me in understanding why notify() is sending notification to all waiting threads.

    Many thanks in advance.

    CODE:

    ------
    // reader class

    class Reader extends Thread
    {
    Caliculator calc;

    public Reader (Caliculator c)
    {
    calc = c;
    }

    public void run()
    {
    synchronized(calc)
    {
    try
    {
    System.out.println(Thread.currentThread().getName() + " is waiting ....");
    calc.wait();
    System.out.println(Thread.currentThread().getName() + " got notified ..");
    System.out.println(Thread.currentThread().getName() + " - total : " + calc.sum);

    }
    catch(InterruptedException ie) {}
    }

    }

    public static void main(String [] args)
    {
    Caliculator cal = new Caliculator();
    Reader r1 = new Reader(cal);
    r1.setName("Reader-1");
    Reader r2 = new Reader(cal);
    r2.setName("Reader-2");
    Reader r3 = new Reader(cal);
    r3.setName("Reader-3");

    cal.start();
    r1.start();
    r2.start();
    r3.start();



    System.out.println("Program ends here");
    }
    }

    //caliculator class

    class Caliculator extends Thread
    {
    int sum=0;
    public void run()
    {
    synchronized(this)
    {
    for (int index=0;index < 100 ; index++)
    {
    sum +=index;
    }
    try
    {
    Thread.sleep(2000);
    }
    catch(InterruptedException ex)
    {
    }

    notify();
    }
    }
    }

    ------------------------------------------------------------------------

    output:


    Reader-1 is waiting ....
    Reader-2 is waiting ....
    Reader-3 is waiting ....
    Reader-2 got notified ..
    Reader-2 - total : 4950
    Reader-1 got notified ..
    Reader-1 - total : 4950
    Reader-3 got notified ..
    Reader-3 - total : 4950

    ----------------------------
     
    mallikk, Oct 22, 2007
    #17
  18. vj

    jessie143143

    Joined:
    Oct 21, 2012
    Messages:
    1
    notify causes only one thread to wake up while notify all causes all threads that are in waiting state to wake up
     
    jessie143143, Oct 21, 2012
    #18
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. mohammed rafi
    Replies:
    3
    Views:
    14,509
    Charles Bailey
    May 7, 2004
  2. mohammed rafi
    Replies:
    1
    Views:
    1,343
    ben cohen
    May 6, 2004
  3. VisionSet
    Replies:
    13
    Views:
    3,937
    Filip Larsen
    Jul 13, 2004
  4. ITpro
    Replies:
    2
    Views:
    2,622
    David N. Welton
    Oct 29, 2005
  5. mallikk
    Replies:
    0
    Views:
    639
    mallikk
    Oct 24, 2007
Loading...

Share This Page