473,465 Members | 1,405 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Synchronization of methods in java

77 New Member
Am having difficulty in understanding how code given in Complete ref. of Java

Expand|Select|Wrap|Line Numbers
  1. class book
  2. {
  3.     int n;
  4.     boolean val=false;
  5.     synchronized int get()
  6.     {
  7.         while(!val)
  8.         {
  9.             try
  10.             {
  11.                 wait();
  12.             }
  13.  
  14.         catch(InterruptedException e)
  15.         {
  16.             System.out.println("Caught the exception"+e);
  17.         }
  18.         }
  19.         System.out.println("Got:"+n);
  20.         val=false;
  21.         notify();
  22.         return n;
  23.     }
  24.     synchronized void put(int n)
  25.     {
  26.         while(val)
  27.         {
  28.             try
  29.             {
  30.                 wait();
  31.             }
  32.         catch(InterruptedException e)
  33.         {
  34.             System.out.println("Caught the exception"+e);
  35.         }
  36.         }
  37.         this.n=n;
  38.         val=true;
  39.         System.out.println("Put:"+n);
  40.         notify();
  41.     }
  42. }
  43. class producer implements Runnable
  44. {
  45.     book b;
  46.     producer(book b)
  47.     {
  48.         this.b=b;
  49.         new Thread(b,"producer").start();
  50.     }
  51.     public void run()
  52.     {
  53.         int i=0;
  54.         while(true)
  55.         {
  56.             b.put(i++);
  57.         }
  58.     }
  59. }
  60. class consumer implements Runnable
  61. {
  62.     book b;
  63.     consumer(book b)
  64.     {
  65.         this.b=b;
  66.         new Thread(this,"consumer").start();
  67.     }
  68.     public void run()
  69.     {
  70.         int i=0;
  71.         while(true)
  72.         {
  73.             b.get();
  74.         }
  75.     }
  76.  
  77. }
  78. class PCfixed
  79. {
  80.     public static void main(String a[])
  81.     {
  82.         book b=new book();
  83.         new producer(b);
  84.         new consumer(b);
  85.         System.out.println("Press control-c to stop!");
  86.     }
  87. }
This code works as stated in book;
value gets put by producer and consumed by consumer.
put:1
get:1
..so on..
how come book class gives no error ; as its using notify(),wait() functions of Thread class without extending it.
Next one is when we call producer(b); it goes in its constructor; which calls start ;taking execution in run() of it.. which calls put(i); in which while loop doesnt execute as value is set to false so by wait() it'll go to get and hence consumer will work 1st...so, where am i mistaking?
Jan 28 '10 #1

✓ answered by pbrockway2

What the API docs say is "Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method)".

Think of it like a person starting a race. This person causes calls a start method for each of the race participants (each of whom begin to run). But now we have multiple threads going simultaneously: one for each race participant and one for the starter.

The important thing is that the starter does not have to wait around at the side of the track while the race is being run. They are in their own thread and go on to do ther things once they have invoked the particpant's start().

12 2235
pbrockway2
151 Recognized Expert New Member
@Time
notify() - "Wakes up a single thread that is waiting on this object's monitor" - and wait() - "Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object" - are methods of Object not Thread.
Jan 28 '10 #2
pbrockway2
151 Recognized Expert New Member
@Time
put() gets called from the run() method of the producer as you say.

Now in put() the waiting only happens when (and while) val is true. If val is false the put() method goes on and prints the console message.

Perhaps I am missing what you are confused about.
Jan 28 '10 #3
Time
77 New Member
exactly.. put will work when value of val is true but when we call it for the first time its value is false... as its set to false in book class..
But in output put method works first; i.e. it displays the value first and same one is accepted by get.. after put has done with displaying value..
but according to the code, put is not the one which will execute first..
Jan 29 '10 #4
pbrockway2
151 Recognized Expert New Member
put will work when value of val is true
No - put() will wait while val is true. That's what "while(val){wait();}" means. put() will print the console message after val has stopped being true. Ie when val is false.

The first time put() is called val is false so no wait()ing happens. But the rest of the put() method - the four lines after the while block - occurs as normal.
Jan 29 '10 #5
Time
77 New Member
Thanks a lot...it was really very helpful..i was missing the main point..
But i guess am still confused about what exactly will be the sequence of execution..
I'll write down what i make out of execution sequence; you point out where am i going wrong.. if it is ok with you.
1.Object of book is created with default constuctor.
2.Object of producer is created; it calls constuctor of it; which is having start method; which makes execution go in run() of producer,..where the val is false so wait won't get called; and one value will be displayed...after that notify() will wake up the thread that is in objects monitor.....But till now only put() has been called and its not in wait() state; so no point of waking it up...and further put is in while loop so how come it will ever call get...the next line of code.... even if we use wait; inside run of producer the while condition is always true; without letting execution go out of it... ???messed up
Jan 30 '10 #6
pbrockway2
151 Recognized Expert New Member
1.Object of book is created with default constuctor.
2.Object of producer is created; it calls constuctor of it; which is having start method; which makes execution go in run() of producer,..where the val is false so wait won't get called; and one value will be displayed...after that notify() will wake up the thread that is in objects monitor...
OK. The notify picks one of the threads that might be waiting (if there is one) and takes it out of its "waiting" state.

But till now only put() has been called
I'm not sure about that. We don't know if the consumer thread has been created and started at this point. Remember main() and the creation of the objects happens in one thread and the put()s and get()s all happen on other threads. When notify is called the other other thread may or may not have called get(): we don't know.

and its [put()'s] not in wait() state; so no point of waking it up...
Yes. The thread executing put() is not waiting. So it doesn't get woken. Actually there is no mystery what put() does once it calls notify(): it returns! put() has finished.

and further put is in while loop so how come it will ever call get.
I don't understand what you mean by this. put() has returned and is finished. The wait while loop has well and truly finished. Execution has passed back to producer's run() method. Is that the while loop you are talking about?

That loop continually calls put() - but get() still gets called ... in another thread! (the consumer thread that gets created eventually).

...the next line of code.... even if we use wait; inside run of producer the while condition is always true; without letting execution go out of it... ???
I'm not sure I understand what you are getting at here. But you seem to be losing sight of the fact that there are two different threads here. (not counting main() which is in a third thread). Try following the flow from line to line with your finger. But the thing is you'll have to use two fingers because there are two threads.

It's almost like two programs happening at once. One of them gets into a tight loop "while(true){get();}" and one of them gets into a tight loop "while(true){put();}". Different fingers are pointing to these different while loops. Both are happening.

Occasionally the flow of code being traced by each finger will be made to wait (until val has a certain value) but, other than that, both fingers (threads) trace their own, independent, paths through the code.
Jan 30 '10 #7
Time
77 New Member
Please check this as well.
Is it the case that; as put and get are in Q class; they are in Q object's monitor.. am bothered about objects monitor; as notify() will wake-up a thread which is in objects monitor..
If am right till this point..after executing put() once..notify() will return as you said..
so; is it the case that as soon as notify() is executed; get can now access the resources..i.e. variables of Q class; meaning val which is now true; making get to come out of its while(!val) {..} loop; and get will be executed now..and at the same time put is in wait state but as get is executed once it will notify() and then put will come out of its wait state..
so the same procedure will continue...
Last thing am not clear about is; what exactly makes a program run more than one thread i.e. functions...is it because we have implemented runnable in producer and consumer... but what is making main() not to wait till producer class is done with creating object and execute the next line simultaneously? its not implementing runnable..is it because it has called producer and producer is the one which is implementing runnable; so it gives main() freedom to execute next line without letting finishing the present one first??
Jan 31 '10 #8
pbrockway2
151 Recognized Expert New Member
I'm not 100% sure about what you're saying in the first paragraph, but it sounds right...

As for what allows the program to begin with one thread (where main() runs) but create multiple threads, and for main() to "keep going", as it were, without having to wait: I think the answer lies in the fact that start() returns immediately. main() calls a constructor which in turn creates and starts a new thread. The constructor returns and main() is free to continue.
Jan 31 '10 #9
Time
77 New Member
But how come start() can return immediately? I mean it is the one which implicitly calls run()...am not sure whether it actually calls; or some method is used.. i suppose it calls as execution goes in run().. so start() is calling run(); it can't return until run() is done..?
Feb 1 '10 #10
pbrockway2
151 Recognized Expert New Member
What the API docs say is "Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method)".

Think of it like a person starting a race. This person causes calls a start method for each of the race participants (each of whom begin to run). But now we have multiple threads going simultaneously: one for each race participant and one for the starter.

The important thing is that the starter does not have to wait around at the side of the track while the race is being run. They are in their own thread and go on to do ther things once they have invoked the particpant's start().
Feb 1 '10 #11
Time
77 New Member
Thanks a lot PBROCKWAY2.
it was really very helpful.
Feb 2 '10 #12
pbrockway2
151 Recognized Expert New Member
You're welcome.

(this portion added to lengthen the post...)
Feb 2 '10 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Michael Ekstrand | last post by:
I've been googling around for a bit trying to find some mechanism for doing in Python something like Java's synchronized methods. In the decorators PEP, I see examples using a hypothetical...
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
5
by: Cyrus | last post by:
I have a question regarding synchronization across multiple threads for a Hashtable. Currently I have a Threadpool that is creating worker threads based on requests to read/write to a hashtable....
1
by: Christoph Nahr | last post by:
The task: I want to let a background thread and a Windows Forms foreground thread communicate via callback methods. Now synchronization of a *single* delegate works just fine with the usual...
5
by: fei.liu | last post by:
Hello, in the application I am developing, I am having trouble to synchronize event triggered actions using 'lock(ob){...};' technique. Here is a outline of my code: class C{ int x = 0; public...
5
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the...
6
by: Chris Ashurst | last post by:
Hi, I'm coming in from a despised Java background, and I'm having some trouble wrapping my head around sharing an object between multiple instances of a single class (in simpler terms, I would say...
4
by: hostel | last post by:
import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrator */ public class sync { public static void main(String args)
6
by: Dmitriy V'jukov | last post by:
On 2 ΑΧΗ, 20:47, "Dmitriy V'jukov" <dvyu...@gmail.comwrote: Q: Can I use Relacy Race Detector to check my algo againts other that C ++0x memory models (x86, PPC, Java, CLI)? A Yes, you...
3
by: CKKwan | last post by:
Dear All, Can synchronize a class, any function is called and the entire class is locked. Can synchronize a method What if I need to Lock a class only when specific method is call?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.