Diffrence Between Notify & NotifyAll ?

V

vj

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
 
F

Fred

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
 
V

vj

notifyAll wakes up a larger candidate pool of threads - any of thosebut 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
 
C

Chris Smith

vj said:
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
 
T

Thomas Hawtin

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.
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
 
C

Chris Uppal

Thomas said:
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
 
C

Chris Smith

Chris Uppal said:
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
 
V

vj

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
 
C

Chris Smith

vj said:
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
 
C

Chris Smith

Thomas Hawtin said:
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
 
J

John C. Bollinger

Chris said:
Thomas Hawtin said:
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.
 
C

Chris Smith

John C. Bollinger said:
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
 
V

vj

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.
 
C

Chris Smith

vj said:
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
 
C

Chris Uppal

Chris Smith wrote:

[me:]
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 ?

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
 
T

Thomas Hawtin

vj said:
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
 
Joined
Oct 22, 2007
Messages
2
Reaction score
0
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

----------------------------
 
Joined
Oct 21, 2012
Messages
1
Reaction score
0
notify causes only one thread to wake up while notify all causes all threads that are in waiting state to wake up
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top