File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes another thread doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "another thread doubt " Watch "another thread doubt " New topic
Author

another thread doubt

amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
hi i didn't understand the following stuff at all....
its from K&B.. and i read it many times ...
and after reading it 5-6 times ...
didnt clear it fully...

please anybody explain me ....here it goes

=============================================================Let’s take a look at some real code
that shows one object waiting for another object to notify it (take note, it is somewhat
complex):
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. }
This program contains two objects with threads: ThreadA contains the main thread
and ThreadB has a thread that calculates the sum of all numbers from 0 through 99.
As soon as line 4 calls the start() method, ThreadA will continue with the next
line of code in its own class, which means it could get to line 12 before ThreadB has
finished the calculation. To prevent this, we use the wait() method in line 9.
Notice in line 6 the code synchronizes itself with the object b—this is because in
order to call wait() on the object, ThreadA must own a lock on b. For a thread to
call wait() or notify(), the thread has to be the owner of the lock for that object.
When the thread waits, it temporarily releases the lock for other threads to use, but
it will need it again to continue execution. It is common to find code such as the
following:
synchronized(anotherObject) { // this has the lock on anotherObject
try {
anotherObject.wait();
// the thread releases the lock and waits
// To continue, the thread needs the lock,
// so it may be blocked until it gets it.
} catch(InterruptedException e){}
}
The preceding code waits until notify() is called on anotherObject.
synchronized(this) {
notify();
}
This code notifies any thread currently waiting on the this object.
The lock can be acquired much earlier in the code, such as in the calling method.

==============================================================

i will be gr8full


Thanks and Regards, Amit Taneja
Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
Posts: 195
When wait() is called, the main thread of execution (ThreadA) stops executing and goes into a waiting state. ThreadA gives up its lock on the b object and waits to be notified that it can try to regain the lock on b and continue executing. Since that thread went into a waiting state and gave up its lock on b, the other thread (ThreadB), whose code is synchronized on the b object, can execute. When ThreadB calls notify(), the waiting thread (ThreadA) gets notified that it should stop waiting. ThreadB's synchronized code ends, so it releases its lock on b. ThreadA grabs that lock and resumes executing from where it left off.
[ April 23, 2005: Message edited by: Joe Sanowitz ]

SCJA 1.0 (98%), SCJP 1.4 (98%)
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
thanx joe

so does that means both thread are in synchornization mode using object b so when one ( say Thread A ) goes to waiting other thread takes over it and will start execution till it completes or notifies the first one ( Thread A)
??

One more thing .. is thread lose its lock on object when it goes in waiting state..?
as in Thread A may be doing in above ?

please clear my doubt

thanx
[ April 23, 2005: Message edited by: amit taneja ]
Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
Posts: 195
so does that means both thread are in synchornization mode using object b so when one ( say Thread A ) goes to waiting other thread takes over it and will start execution till it completes or notifies the first one ( Thread A)??


You can see that both threads have portions of code that are synchronized because of line 6 and line 20 where the keyword synchronized is used to label a method or block.

Yes, they are both synchronized on the same object. In the context of ThreadA's main method, that object is referenced by a variable named b. In the context of ThreadB's run method, that same object is referenced by the keyword this.

When ThreadA goes into a waiting state, it releases its locks. Any other thread that wants to take the lock on b is free to do so. ThreadB takes the lock so its synchronized block can execute. When notify is called on the this object, ThreadA stops waiting and tries to reclaim the lock on b that it needs in order to continue executing.

Note that notify does not make the lock available. All notify does is tell ThreadA to stop waiting, and to try to reclaim the lock. What makes the lock available is the fact that ThreadB's synchronized block ends. That's when ThreadA succeeds in reclaiming the lock.

One more thing .. is thread lose its lock on object when it goes in waiting state..?
as in Thread A may be doing in above ?


Yes, that's correct.
soumya ravindranath
Ranch Hand

Joined: Jan 26, 2001
Posts: 300
Hi Joe,

I inserted some comments and ran the code.



I get varied outputs on different runs.

Two of them are as below -
-------------------------
a)

just after b.start
Waiting for b to complete...
inside b.run...
before b.notify
Total is: 4950
Outside b's synchronized block...

b)

inside b.run...
before b.notify
Outside b's synchronized block...
just after b.start
Waiting for b to complete...
-----------------------------------

As soon as b.start() is called from the main thread, we cannot assume that the next line of code in ThreadA will be executed and ThreadA will secure the lock on b and hence go in to wait mode and so on. Am I right ?

Looking at the output of the second execution, I see that the main thread calls b.start() and immediately, run method is executed (can I say "ThreadB secures the lock on b" ? ), right ? The synchronized block completes, notifies and comes out. The main thread gets into synchronized block and goes in to wait mode. And hangs...

Is my understanding of the situation correct ? My question is, how can they assume that ThreadA will wait for ThreadB to finish calculation ?

Thanks,
Soumya.
[ April 24, 2005: Message edited by: soumya ravindranath ]
soumya ravindranath
Ranch Hand

Joined: Jan 26, 2001
Posts: 300
Is anyone interested in replying ?
Thanks,
Soumya
Kalyani Marathe
Ranch Hand

Joined: Apr 06, 2005
Posts: 72
I have expected the same result as here we don't have synchronized method just block. So result should be varying. But I have heard everybody saying that after b.start() it will execute next line so in this sense the result is right.

Can somebody clarify that result will be same or varying?

Thanks.
Jagadesh cs
Ranch Hand

Joined: Apr 25, 2005
Posts: 50
As soon as start() is called the new thread will be created and which thread runs after that depends on the JVM . We cant assume that a particular thread will run or that the output will be same!!

Soumya your understanding of the situation seems to be fine


Cheers,<br />Jagadesh.<br /> <br />--------------------------------<br />SCJP 1.4 , SCBCD 1.3 , SCWCD 1.4<br />--------------------------------
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
so the answer is unpredictable can i say that
Jagadesh cs
Ranch Hand

Joined: Apr 25, 2005
Posts: 50
i guess you can !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: another thread doubt