File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes wait and notify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "wait and notify" Watch "wait and notify" New topic
Author

wait and notify

ram kumar
Ranch Hand

Joined: May 22, 2008
Posts: 146
Hi Pals,

Hope this time you will spare your patience for me.

Thanks for your support.

I have 2 threads - both accessing the same method - instanceMethod();

Any particular time i need only one thread accessing the method.

The other thread must wait untill the current thread completes.

I will not use synchronized.

I need to do it with wait() and notify();

Please have a look over the code.












Also, would some one explain me.

# I say wait and notify is an alternative to synchronized.

# what is object lock ?

# What is yield()/suspend()/pause()

it sounds the same.












Discussion - the powerfull way to excellence!
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57
Hi Ram,
wait and notify are not alternative to synchronized. Infact wait(), notify() and notifyAll() should be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.
ram kumar
Ranch Hand

Joined: May 22, 2008
Posts: 146
Originally posted by Shahnawaz Shakil:
Hi Ram,
wait and notify are not alternative to synchronized. Infact wait(), notify() and notifyAll() should be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.


Thanks for the response !

Would you give me an code example of acccessing a common area (ex:method)

from 2 threads so that, they go on with a wait and notify calling one

another.

How do i lock an object ?

Do you mean to say that once i lock an object then i wont be able to call any other method over the object;

untill the lock is released.,

When do i say an object is locked / released ?

Please help me with some code samples.

I feel, Book examples are tough.

Some one, Help me out with simple examples.
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57
Before i give you example i think we should be very clear about syncronized, wait and notify.
You can synchronize one or more method of a class (actually even just a block of code but leave it for now). When you synchronize a method it means you are telling the JVM that a thread needs to acquire the lock of the object before it can call this method. Since an object can have only one lock so if a thread is accessing a synchronized method, then no thread can access any of the synchronised method of that object. Though they can call those methods of the object which are not synchronized.Typically, releasing the lock means the thread holding the lock (the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.
Now to understand wait() and notify() you can refer following example which is easy to understand. Here we have two classes named ThreadA and ThreadB. The main method in class ThreadA is printing the sum of i starting from 0 to 100. But this calculation is being done in the run() method of class ThreadB. So obviously main() method should wait for run() to complete so that it can print the total. Here comes the use of wait() method. And now you can understand why wait and notify should by called in synchronized context. When the thread waits it temporarily releases the lock for other threads to use but it will need it again to continue its execution. So once the thread which is waiting is notified (by notified method) it then starts comepting to acquire lock so that it can complete the remaining part of the method.
[code]
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. }
12. System.out.println("Total is: " + b.total);
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
[code]
Hope this is helpful
ram kumar
Ranch Hand

Joined: May 22, 2008
Posts: 146
Originally posted by Shahnawaz Shakil:
Before i give you example i think we should be very clear about syncronized, wait and notify.
You can synchronize one or more method of a class (actually even just a block of code but leave it for now). When you synchronize a method it means you are telling the JVM that a thread needs to acquire the lock of the object before it can call this method. Since an object can have only one lock so if a thread is accessing a synchronized method, then no thread can access any of the synchronised method of that object. Though they can call those methods of the object which are not synchronized.Typically, releasing the lock means the thread holding the lock (the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.
Now to understand wait() and notify() you can refer following example which is easy to understand. Here we have two classes named ThreadA and ThreadB. The main method in class ThreadA is printing the sum of i starting from 0 to 100. But this calculation is being done in the run() method of class ThreadB. So obviously main() method should wait for run() to complete so that it can print the total. Here comes the use of wait() method. And now you can understand why wait and notify should by called in synchronized context. When the thread waits it temporarily releases the lock for other threads to use but it will need it again to continue its execution. So once the thread which is waiting is notified (by notified method) it then starts comepting to acquire lock so that it can complete the remaining part of the method.
[code]
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. }
12. System.out.println("Total is: " + b.total);
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
[code]
Hope this is helpful



That was informative !.

Will try to come out with my own example !
Mahan Hooshmand Rad
Greenhorn

Joined: Mar 15, 2006
Posts: 2
I ran this exact code on linux but the notify() method does not wake up the thread 95% of times.
I used both Ubuntu and Arch....
Could it be really the OS architecture? really confused.
I'm already disapointed in notify() method.
Had to work on all architectures..
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
Well it makes sense that it does not always work. You have to think how threads work in Java, very little is guaranteed.

There are two main ways this code could execute:
Line 4 executes, but ThreadB does not get chosen to run, it merely sits in the Runnable pool.
ThreadA continues and gets the lock on ThreadB, then waits thus entering the Waiting pool.
ThreadB is then chosen to run (it's the only other tread after all), then notifies ThreadA that it is done.
ThreadA generates the result.
OR
Line 4 executes and for whatever reason the thread scheduler decides that ThreadA should go back to the Runnable pool and ThreadB should run.
ThreadB runs, completes and notifies that it is done. But no one is listening, ThreadA never got the lock, it's not in the Waiting pool; it's in the Runnable pool.
ThreadA is then chosen to run, locks on ThreadB and waits to be notified.
This notification never comes because ThreadB is already done.

This can be solved simply enough my moving line 4 "b.start()" to with the synchronised block. Then you guarantee that ThreadA will have the lock, start ThreadB and even if ThreadB gets chosen to run it will be immediately blocked by ThreadA's lock. ThreadA then waits (releasing the lock) and ThreadB can be chosen to run. The notification will always be heard because ThreadA is sat in the Waiting pool, waiting for it.

Oh, and one other thing; it's usually better to use "notifyAll()" rather than "notify()" unless you are sure that one thread (and only ever one thread) will be waiting. If 10 threads were waiting, "notifyAll()" will tell them all, "notify()" will only tell one (which is bad) and you have will have no idea which one that would be (which is worse!). Whenever I see threads, a little voice in my head says "Danger, Will Robinson!"


SCJP6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
Think this would sit better on the Threads forum. Moving.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait and notify