• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

From Velmurugan's Notes

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
"NotifyAll moves all threads in the monitor�s waiting pool to ready."
I am little bit confused here. Is all the threads goes to ready state? I think only one thread aquires the object lock, and goes to ready state .
Please explain .
Thanking you
Rose
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rosemol,
"notifyAll()" wakes up all the threads waiting for the object lock; the threads compete for the lock; the 'winning' thread starts to 'run' and the others are returned to the 'wait pool' until another notify is sent.

Hope that helps.

------------------
Jane Griscti
Sun Certified Java 2 Programmer
 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
notifyAll moves all threads in the waiting pool to Ready state, and they compete again to acquire the monitor's lock. The thread that acquired the lock gets to execute. Others return to the
waiting pool.
notify moves one thread in the waiting pool to Ready state,
and we cannot be sure which thread it is.
HTH
------------------
Velmurugan Periasamy
Sun Certified Java Programmer
----------------------
Study notes for Sun Java Certification
http://www.geocities.com/velmurugan_p/
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Velmurugan Periasamy,

RHE says (P.205)
Ready : Not waiting for anything except the CPU.
As you said seeking for lock is going on in the ready state?
RHE says a waiting thread after seeking for lock and obtaining lock the thread enters to Ready state.
this is what I can't understatnd.
Could you explain a little bit more.
Thanking you
Rosemol
 
Velmurugan Periasamy
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think this is what happens. Correct me if I'm wrong.
1. Call to notifyAll.
2. All threads waiting in the pool moved to Ready state.
3. Thread scheduler picks one thread to execute, others return to the pool.
4. The thread that gets to execute, must re-acquire the lock of the monitor - and this is a responsibility of the programmer. That's why you have to check the monitor's state in a while loop rather than an if statement. Otherwise there's a possibility that threads might be corrupting the shared data.
HTH

------------------
Velmurugan Periasamy
Sun Certified Java Programmer
----------------------
Study notes for Sun Java Certification
http://www.geocities.com/velmurugan_p/
 
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From JLS:


The notifyAll method should be called for an object only when the current thread has already locked the object's lock. Every thread in the wait set for the object is removed from the wait set and re-enabled for thread scheduling. (Of course, those threads will not be able to proceed until the current thread relinquishes the object's lock.)


I want to emphasis that notifyall() can only be called when the current thread has already locked the object's lock.
Next sentence is important: Every thread in the wait set for the object is removed from the wait set and re-enabled for thread scheduling.
Velmurugan #2 says "All threads..." which is incorrect. All threads waiting on the same locked object gets awaken from the "dormant" pool and moved to the ready state.
-Peter
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Peter,
"Every thread in the wait set for the object is removed from the wait set and re-enabled for thread scheduling."
That means those threads in the wait set for the object is now in Reday state.And only one thread gets object lock.

What happens to other threads ?
Jane and Velmurugan says they are return to waiting pool of the object.
But IMHO they won't. When I wrote some code it seems to me that "They remains in Ready State competing for object lock."
They are not returning to waiting pool to get notify again.
Can you please verify this?
Thanking you
Rosemol.

 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rosemol,
The following is from the Sun Tutorial on Threads (emphasis added)

The notifyAll method wakes up all threads waiting on the object in question (in this case, the CubbyHole). The awakened threads compete for the lock. One thread gets it, and the others go back to waiting.

Hope that helps.

------------------
Jane Griscti
Sun Certified Java 2 Programmer
[This message has been edited by Jane Griscti (edited February 06, 2001).]
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jane! I had a feeling the remaining threads go back into a wait state, and I was going to write a little test program to test it out. Thanks to you I don't have to anymore.
-Peter
 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i got my funde clear in threads thru the discusions on thread at maha's site. in one of the posts she paints a very vivid analogy with a restaurant situation to explain notify and notify all.
read that and you'll never have to read anything else again. believe me!
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your welcome Peter. Found a little further clarification in Concurrent Programming in Java Second Edition: Design Principles and Patterns.
"The wait set for each object is maintained internally by the JVM. Each set holds threads blocked by wait on the object until corresponding notifications are invoked or the waits are otherwise released pg 184
"A notify invocation results in the following actions:

  • If one exists, an arbitrarily chosen thread, say T, is removed by the JVM from the internal wait set associated with the target object. There is no guarantee about which waiting thread will be selected when the wait set contains more than one thread.
  • T must re-obtain the synchronization lock for the target object, which will always cause it to block at least until the thread calling notify release the lock. It will continue to block if some other thread obtains the lock first
  • T is then resumed from the point of its wait.

  • pg 185
    It goes on to say that "notifyAll works in the same way as notify except that the steps occur for all threads in the wait set for the object
    As they're saying wait blocks the thread and in the notify that a thread will continue to block if another thread obtains the lock; think it's fairly safe that what the tutorial says is correct: when one thread gets the lock, the others return to the wait state.
    Bit of overkill ... I know but the terminilogy was bothering me. If the ready state means the thread is available to the thread scheduler then you could say all the threads move from wait to ready and then back to wait if the don't acquire the lock.

    ------------------
    Jane Griscti
    Sun Certified Java 2 Programmer
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jane,
Thank you for your explanation.

After notifyAll ,Only one thread obtains the object lock . All otres will surely wait for lock. I agree with this.
The question is
Whether The threads fails to aquire lock goes to waiting pool .And continue to wait to get another notify ?

While I coding , it seems to me that all the threads get out of the waiting pool due to notifyAll() call will remain in Ready state. When they get object lock they will continue to excute.
My code :

Rosemol.

 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hmm...Okay, I wrote a test program anyway.
Jane, from the tutorial I was thinking that only one thread gets the lock and the other threads will go back into a wait state. Since they're all in a wait state, I would think you need to invoke another notify() or notifyAll() to get them out. This doesn't seem to be the case.

The output:
Invoking Worker.wait() on Thread.name: Thread-0
Invoking Worker.wait() on Thread.name: Thread-1
Invoking Worker.wait() on Thread.name: Thread-2
Invoking Worker.wait() on Thread.name: Thread-3
Printing Thread.name: Thread-0
Printing Thread.name: Thread-1
Printing Thread.name: Thread-2
Printing Thread.name: Thread-3
When I execute a notifyAll(), all the threads wake up and print out their name. If I modify the code to use notify(), only one thread name will print out and the program will hang waiting for the other threads to wakeup (which they never will).
-Peter
 
Velmurugan Periasamy
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following text is also from my notes:


  • Note the differences between blocked and waiting.

  • Blocked Waiting
    Thread is waiting to get a lock on the monitor. (or waiting for a blocking i/o method) Thread has been asked to wait. (by means of wait method)
    Caused by the thread tried to execute some synchronized code. (or a blocking i/o method) The thread already acquired the lock and executed some synchronized code before coming across a wait call.
    Can move to ready only when the lock is available. ( or the i/o operation is complete) Can move to ready only when it gets notified (by means of notify or notifyAll)


Initially the threads are in waiting state(They all are trying to execute some synchronized code since they already have called wait). notifyAll moves all of them to Ready state. They compete for the lock, the thread that gets the lock continues to execute.
Others didn't get the lock, so they're all blocked(It's also like waiting, but not technically in the waiting state). That's why they don't need another notify/notifyAll. When the lock is available, they come out of the blocking state and execute.(Again all threads will compete for the lock, and whichever thread gets the lock will execute, and this will continue..)
Thanks for clarifying it.
------------------
Velmurugan Periasamy
Sun Certified Java Programmer
----------------------
Study notes for Sun Java Certification
http://www.geocities.com/velmurugan_p/
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From these test programs, it would seem that the Java Tutorial is wrong when it states:



One thread gets it, and the others go back to waiting.


-Peter
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
Peter, Rosemol, good examples. Looks like you're right; they are blocked but in ready state vs wait state.
Thanks for posting the question Rosemol
------------------
Jane Griscti
Sun Certified Java 2 Programmer
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jane ,Peter ,Velmurugan,
Thank you for clarifying my doubt.I apreciate your time and effort.
To conclude on RHE :Page 219 they provided a diagram to show monitor state.
They says after notify()/notifyAll() the threads goes to seeking lock state. Is there a seeking for lock , is actually happening before entering Ready state?
From the above discussions, IMHO they are directly goes to Ready state .
[ and remains blocked from executing till scheduler picks the thread and assign the object lock.]
Is the RHE diagram is right? IMHO it must be modified.
It would be great help if you can verify this also ?
Thanking you
Rosemol.
 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rosemol Thanjappan, Jane Griscti, Velmurugan Periasamy, Peter Tran,
I am V.Srinivasan, an aspirant to become an SCJP.
I would like clarify you all about notify() method by modifying Peter Tran's code:
code:

class Worker implements java.lang.Runnable {
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println("Invoking Worker.wait() on Thread.name: " + threadName);
synchronized(this) {
try {
this.wait();
}
catch (java.lang.InterruptedException e) {
}
print();
}
} // run()
public void print() {
String threadName = Thread.currentThread().getName();
System.out.println("Printing Thread.name: " + threadName);
}
} // class Worker
public class Queen {
public static void main(String[] args) {
Worker w = new Worker();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
Thread t4 = new Thread(w);
t1.start();
t2.start();
t3.start();
t4.start();
// Put current thread to sleep for 5 seconds to give worker threads to run.
try {
Thread.sleep(5000);
}
catch (java.lang.InterruptedException e) {
}
while(t1.isAlive() | | t2.isAlive() | | t3.isAlive() | | t4.isAlive()) {
synchronized(w) {
// Wake all worker threads up and see who gets to run first.
w.notify();
}
}//while ends
} // main()
} // class Queen

Java Tutorial (or any book) is not wrong. We can verymuch call notify() method as we need. I think this is best approach to catchhold of a live thread. I hope this would help you all.
Regards,
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
V,
I'm not sure I understand what you're trying to prove. Your modification just makes sure you call notify() enough time to get all the threads to move out of the wait state and have the program terminate.
This isn't a very good practice, because in a many consumer and many producer scenario, you may have deadlock if you only wake one thread up at a time. Or only the same thread gets to run and the other threads may never get to run. Remember, you can't determine which thread will get notified. You're only guaranteed that only 1 thread gets notified. Furthermore, does this mean your while(someThread.isAlive()) loop has to run forever? Even if I'm sure I only have one thread waiting, I still use notifyAll().
-Peter
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
V,
In Peter Haggar's excellent book, Practical Java, he says in Praxis 55: "Use wait and notifyAll instead of polling loops." Sir Haggar gives many reasons why you want to use notifyAll(). I highly recommend getting a copy for yourself.
-Peter
 
V Srinivasan
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Peter,
I agree with your points and thanks for suggesting Peter Haggar's book, I will try get a copy of that.
In your code it is very obvious, there are only four objects created for the Worker class, we can verymuch manipulate these threads. I have not argued notify() is the best method not notifyAll(), my intention is wherever necessary and possible we can appropriately use notify() according to our need, and we can use it in your code if we call notify(). In a volume of threads, I agree it is very difficult, we have less options to manipulate the threads. But still we have some good options/methods to manipulate large amount of threads, say, we can create threadgroup, array of threads, we can name them and change priority of particular thread, we struck at the same priority thread there we don't know which thread will get monitor, etc. But, notify() is not a meaningless method, thats what I want to say. Thank you very much.
Regards
 
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
This was a good discussion on Threads.
to conclude
When NotifyAll() is called on on object then all the threads waiting for lock on this object goes into the ready to run state and one arbitary thread gets the lock and starts executing.And all other threads goes into the seeking lock state or blocked state.
Am i correct
I have read in book that it is better to call notifyAll() than notify().But if that is the case then we dont need a seperate wait and blocked state we need just a blocked state where all the waiting threads will go. But i suppose this will take some resources for seeking the lock.
So isnt it better to call the notify() method.
I want to get one more doubt clarified.
I know that when a wait() is called the thread goes into the wait state but will a thread go into the wait or blocked state when it is tries to execute a synchronized block where lock is with another thread.
Wont it be better if all the threads waiting for the lock goes into the wait state and notify() method called at the end of each synchronized block.
I want to know which is a better programming practice
Cherry
 
V Srinivasan
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Cherry,
As simple as we can say notifyAll() identifies all live threads and gives them run state in a synchronised way. But in case of notify() identifies only one arbitrary thread and gives it run state and does nothing after that. So, when handling notify() you have to be careful you should know which thread you want to give run state or leave it to JVM it will execute one arbitrary thread, but you should keep in mind how many thread you have created, whether all threads get run state during the execution of your code, otherwise program will hang because of one or more thread is waiting to get run state. Afterall a thread is created to run, if a thread is not obtaining a run state during execution of the program what is the use of creating a thread object.
To get away from this hastle, simply call notifyAll()
Hi Peter,
Please comment.
Thanks and regards
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
The following are my understanding of
1) Thread execute synchronized keyword
2) Thread execute wait() code
Please feel free to know if you disagree with any of them.
First check what happens
when Thread execute synchronized keyword :
Step 1) Thread is in Ready state.
Step 2) at some instance of time, The thread scheduler picks the thread and assign CPU.
Step 3) Now, Thread is running
Step 4) at some instance of time , synchronized keyword is executed in the thread. it is necessary that the thread to get the object lock of this object or some other specified object.
Step 5) The thread cannot continue until the lock is obtained . So it is blocked from execution .
Step 6) The thread scheduler puts the Thread back to Ready state
Step 7) When the lock is free , The Thread scheduler picks the thread, assigns the lock to this thread and assign CPU.
Step 8) Thread continue executing the synchronized block .
Step 9) When the synchronized block is over ,the object lock is freed .
Step 10) Thread continues executing the other codes.

Next what happens when
Thread execute wait() : .
Lets assume we are at the Step 6 of the Thread execute synchronized keyword .
Step 6) Thread continue executing the synchronized block .
Step 6.1) at some instance of time , wait() is executed in the thread.
Step 6.2) First checks whether this thread is the owner of the object lock on which wait() is called.
If "no " IllegalMonitorStateException is thrown.
If "yes" next step .
Step 6.3) The thread scheduler frees the object lock , and puts the thread in waiting pool of the object.
Every operation about wait() is over Now.
The threads in the waiting pool are waiting for scheduler to get them out of waiting pool.The Scheduler needs notify()/notifyAll/timeout to put them to Ready state. In the wait state they are not waiting for object lock or any thing else they are just waiting for scheduler to get them out of waiting pool.

When some other thread have this object lock, notifies or timeout for waiting is over ,The thread scheduler picks one of the thread from this objects waiting pool and puts the thread in Ready state.
[If it was notifyAll () The thread scheduler picks all of the threads from this objects waiting pool and puts the threads in Ready state.]
Next the thread have to continue the execution of the synchronized code. So continues from Step 7 of the Thread execute synchronized keyword .
Step 7)When the lock is free ,the Thread scheduler picks the thread, assigns the lock to this thread and assign CPU.
Step 8) Thread continue executing the synchronized block .
Step 9) When the synchronized block is over ,the object lock is freed .
Step 10) Thread continues executing the other codes.

Originally posted by Cherry Mathew:

I want to get one more doubt clarified.
I know that when a wait() is called the thread goes into the wait state but will a thread go into the wait or blocked state when it is tries to execute a synchronized block where lock is with another thread.

Wont it be better if all the threads waiting for the lock goes into the wait state and notify() method called at the end of each synchronized block.


Cherry ,

All the threads waiting for the lock ,not goes into the wait state that is "waiting pool " of the object .

Don't confuse with execution of synchronized keyword and execution of wait() .
synchronized keyword : All the threads waiting for the lock, all goes to Ready state, just blocked from execution .When the object lock is free the scheduler picks them and assigns the object lock. There is no need for notify()/notifyAll().
wait() : All threads called wait() goes to waiting pool of the object. Needs notify()/notifyAll/timeout go to Ready state. In the wait state they are not waiting for object lock. They are just waiting for scheduler to get them out of wait state.

Please feel free to know if you agree or disagree with any of them above.
Rosemol.

 
V Srinivasan
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear All,
I sincerely apologise for my unclear post.
Rosemol,
In synchronised code a thread which gets object lock gets monitor (without object lock won't get monitor) and this thread is eligible and it is ready to run and it get executed and scheduler picks this thread only, at a time scheduler picks only one thread, but monitor can block threads when the thread cannot perform its job until an object reaches a certain state and revived after attaining the required state. This monitor blockade is handled by invoking wait() and revived by calling notify(). The most important thing is when it is called wait() method the object relinguishes its object lock and reacquires the object lock when it is called notify and notified thread obtains object lock successfully and other threads remain in waiting pool.
Since it is being called in synchronized block or method concurrent execution is prevented. Because synchronized key word is very powerfull (I presume it directly interacts with JVM and dictates thread scheduler) (otherwise [without synchronized keyword] you will notice an asynchronized behaviour) and that is why it is must to run wait(), notify()/notifyAll() methods in a synchronized block/method.
notifyAll() iteratively calls notify() method for each thread, this is what I presume.
Moreover, wait(), notify() and notifyAll() are related to Object class and these methods are final native methods (which is not written in JAVA) and strict restriction to run within synchronised block/method and we should't play around with these methods much. Only run() method can be overriden.
'seek for lock' state... these are all phrases used to explain us how the transition takes place in the relay of lock change. What I assume is, if it is in an asynchronised way, all threads would be awaken by notifyAll() and all will compete for obtaining object lock and ultimately one will run away, but you cann't do this because you have to call notifyAll() in a synchronised block/method (it is not recommendation, but is restriction). In synchronised way, iteratively notify() method is called and notified thread takes the object lock and run, so that there will not be corruption while execution, but (I agree) you are not sure which thread that would be. If it is not, then just think, why synchronized key word we need, if you put synchronized key word you visualise perfect output, how it happens.
Cherry,
Calling wait() and notify() in a same synchronised block with an argument of THIS, it will work fine, but you have to place them in run() method in a class implementing runnable interface then only the thread object can perform it, but a notify() call in the main method is mandatory. Because, there is only one thread called main is running. When we creat thread object it is basically instantiating the main thread (not main method) and this instance thread registers as "I am akin to main thread and have status as main". The difference between main thread and instance of main thread is main thread can invoke p.s.v.main method, instance of main method can invoke run() method of an object reference of a class which implements runnable ONLY. If you are placing in main method you have to pass the object reference of a class which implements runnable interface as an argument, putting the main method in wait() mode is not correct way, because you can sleep() the main thread, that is the only thing we can do with main thread. And to run the synchronised code of child threads you have to send the main to sleep i.e. while main is in sleep child can perform its synchronized work. If main slept for less time, no way it will hang, you have to increase its sleep time. Remember you have to call notifyAll() method (only) so that you don't need to notify in run method.
This is my understandings on Threads. Please correct me if I am wrong and comment on my understandings.
Thanks.
Please go through the following code:
class Dosomethingelse {
void Doing(){
System.out.println("I am doing something else for Second");}
}
class Worker implements Runnable
{
public void run()
{
System.out.println(this); // We can see Worker Class object's
// instance address. This is how one instance
// multi threads work.
String threadName = Thread.currentThread().getName();
System.out.println("Thread name is "+threadName);
String two = "Second";
Dosomethingelse D = new Dosomethingelse();
while(threadName.equals(two)){ // We can assign particular work to
D.Doing(); // particular thread
two = "";
}

synchronized(this) { // If you put wait this child thread check
try { // whether its main had gone to sleep
String threadname = Thread.currentThread().getName();
System.out.println(threadname+" : I am waiting");
this.wait();
}
catch(InterruptedException e)
{System.out.println(threadName+ " interrupted");}
}
String thName = Thread.currentThread().getName();
System.out.println("Exiting "+thName+" Child");
/*
We can call one notify here and another in main but that is very poor design. It may looks like calling notify here will release thread object's lock, yes it get released here, since it has been called in synchronized code, it wants object passed as argument in thread's object lock also seeks to release, so it would't release, it holds till class object lock is released, it can be released only in main method we can say this state as "ready to die". In a synchronised or nonsynchronised code the thread gets dead state after passing this run block and after class object is notified in main method..
*/
}
}
public class Factory
{
public static void main(String [] msg)
{
String threadName = Thread.currentThread().getName();
System.out.println(threadName+" created");
Worker w = new Worker();
Worker x = new Worker();
Thread t1 = new Thread(x, "First");
Thread t2 = new Thread(x, "Second");
Thread t3 = new Thread(w, "Third");
Thread t4 = new Thread(w, "Fourth");
t1.start();
t2.start();
t3.start();
t4.start();
try { // main thread has to go to sleep then only child can work
// synchronizedly in its sleep time
System.out.println(threadName+" is going to sleep");
Thread.sleep(1000);
}
catch(InterruptedException e) {System.out.println(Thread.currentThread().getName()+" interrupted");}
synchronized(x){ // notify in main method it is mandatory because
x.notifyAll(); } // then only Class objects lock get released
synchronized(w) { // and thread go dead state.
w.notifyAll();}

System.out.println("Exiting Main");
}
}
/*
At a nutshell, thread objects lock get released first and then class objects lock get released and main thread ends this happens because of synchronized keyword.
*/
[\CODE]
[This message has been edited by V Srinivasan (edited February 15, 2001).]
[This message has been edited by V Srinivasan (edited February 15, 2001).]
[This message has been edited by V Srinivasan (edited February 16, 2001).]
[This message has been edited by V Srinivasan (edited February 16, 2001).]
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Srinivasan,
First of all I have a question.
When a thread needs an object Lock ?
Only when it executes synchronized codes of that object (monitors of that object).Yes or No?
if "No" then what are the other situations?

Give me an answer. Then we can proceed to next discussion.
Rosemol.

 
V Srinivasan
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Yes. I made some corrections now.
I may be conceptually wrong I want to correct my understandings, that is the reason I wrote my views.
Thanks and regards,
 
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cant resist posting my views on this topic.
an "explicit notifyAll" puts all waiting thread to ready state. One thread gets the Monitor and other threads "go back to wait state".Now it is important to understand what is this "go back to wait state".
For this we should know how synchronized keyword works. synchronized keyword works by using wait and notify calls in the background( so that the programmer is not aware of it).This means that when one thread is executing other threads will "automatically wait" and be "automatically notified".
So when all threads have been put to ready state by "explicit notifyAll", one of them gets the lock, and other thread go into the "automatic wait" state as a result of synchronized block.
When the monitor becomes available, these threads will be "automatically notified" and execute. There is no need for another "explicit notify/ notifyall".
Hope I am explicit enough.

 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Mohit,

I think ,"explicit notifyAll" works as you wrote.
an "explicit notifyAll" puts all waiting thread to ready state. One thread gets the Monitor and other threads "go back to wait state".

an "explicit notifyAll" puts all waiting thread to ready state. : Who is putting all waiting thread to ready state?
"go back to wait state" : this wait state is actually the "Ready state". am I right?

Hi, Srinivasan,
So you agree a thread needs an object lock only when it tries to execute the synchronized codes of that object(monitor).
Now we check how the "synchronized" key word is executed?
read my post on February 09-th and Mohit's post.
Of course check other posts (like maha, etc) or books(RHE etc )
about what they say about this topic.

Try to answer the questions I wrote above.
Also Which explanation is do you agree or disagree?

Please Post it.
Rosemol.

 
V Srinivasan
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Step 1 : Yes
Step 2 : Yes
Step 3 : Yes
Step 4 : Here you use synchronized key word passing of thread object or class object. One thread gets object lock (it may be thread object lock or class object lock, if it is thread object you can send that thread to go to wait state and notify of Object class(though it is thread afterall it is also an object of Thread) and whatever super class "Thread" permits, example sleep(x), if it is class object you can call that objects variables and methods and whatever super class "Object" permits, example wait(), notify() but remember these methods associated with thread). OK. Why the thread not got the object lock, what I understand, not getting object lock only happens when the system runs with multi-processor (one processor can perform one task only at a time). To perform synchronizedly it blocks (this is what Velmurugan said it is similar to wait state), this state entirely different from sleep, wait.
Step 5 : Yes
Step 6 : No. If it puts back to Ready state, another thread will come with object lock that has to be executed, then synchronization does't take place.
Step 7 : No. When the lock is free synchronized block takes it back to perform for another thread, if it requires and Step 8, otherwise it is free and available to any code can call this object.
Step 8 : Yes
Step 9 : Yes
Step 10 : Yes
Thread execute wait():
Lets assume we are at Step 4 (not Step 6)
Step 6 : (as per your query) Yes
Step 6.1 & 6.2 : Yes in a synchronised block otherwise "IllegalMonitorStateException is thrown
Step 6.3 : Yes, it is waiting to notify, otherwise you will feel like its hanged.
In synchronised code scheduler acts synchronisedly and in nonsynchronised scheduler takes its decision and dispatches.
Step 7 : I don't think scheduler assigns the lock, because lock control done by synchronised key word, scheduler checks if it is in synchronised code it behaves synchronizedly otherwise it dispatches as it picks.
Step 8 : Yes
Step 9 : Yes
Step 10 : Yes thread continues executing other codes related to that object, again if it is thread object codes appearing after the synchronised block in run() method, otherwise the main will be running.
Mohit,
I don't understand what is explicit notifyAll, is there any implicit notifyAll.
My view is notifyAll notifies one waiting thread iteratively i.e. it notifies one thread that thread will run remaining codes or will go to "ready to die state" (it is a new term, please go through my above post) and other thread will run and goto ... and so on till class object lock which is passed as an argument in thread object is released. If one thread notified others are still in waiting pool only (I made correction).
I have poured my thoughts. Tell me where I am wrong (if it is).
Thanks and regards,
 
mohit joshi
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Rose,
You have got it right, as far as the programmer is concerned "go back to wait state" is actually the ready state.
That is why I am using the term "automatic wait/notify".
By "Explicit wait/notify" I mean whenever the programmer has made these calls.
"Automatic wait/notify" is when the vm finds the synchronized blocks and uses wait/notify.
HTH.
Mohit Joshi
 
V Srinivasan
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes Lilly,
I got it, you are right. It was my mind boggling issue for the past one week to "Explicitly" put on pen the flow of the Thread. Am I in the right path of understanding the Thread.
I am waiting Rosemol and others to comment on understanding. I think time is nearing for this THREAD to end.
Thank you very much
V Srinivasan
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mohit,
I am thankful to you for giving me a great relief by agree with me , "go back to wait state" is actually the "Ready state". You are the first agree with me.

But there is a small question is remaining .
I started this thread believing RHE diagram on Page 219 is correct. I believed after the waiting pool all the thread goes to seek lock state before entering Ready State.
But now we all know, all the waited thread directly goes to Ready state.In the Ready state they are competing to get the object lock. In future when they gets object lock they will get executed.
So I think seek locking state explained in RHE is actually the Ready state.Thay shown as 2 different states .I am pretty sure , There is no meaning in differenciating seek locking state between Ready state .

Even if we consider, RHE uses the seek locking state for ease of explanation, The diagram they shown on Page 219 must be modified since they showed only the thread obtaining the lock enters to Ready state what happens to others? The diagram doesnot show any thing about that.

So my last question is

Is the RHE diagram is right?
IMHO it must be modified.
Please try to answer this question.
Thanking you once again,
Rosemol.
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Srinivasan ,

Originally posted by V Srinivasan:
Yes Lilly,
I got it, you are right. It was my mind boggling issue for the past one week to "Explicitly" put on pen the flow of the Thread. V Srinivasan


Yes Srinivasn ,some issues may confuse us for weeks . For me this notifyAll is a an issue for a month now. I nearly read all the post in javaranch about thread ,wait notify ,just for to get my confusion an end.At last I started this thread .
And now atleast Mohit agreed with me "go back to wait state" is actually the "Ready state".
And Only one question remains now.

I am too thinking this thread is going to end very soon.

Rosemol.
 
mohit joshi
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I cant say anything about RHE, I donated my RHE after clearing SCJP. I think it is important to understand the behaviour of Java and not get too concerned with the terminology. You can crosscheck the behaviour by writing small programs yourself.
If RHE says all threads first try to seek lock, that is also correct.It may or may not be appropriate to call it a separate state, (as in different states of the Threads life)
but if multiple thread hit a synchronized block at once, they will all try to get the lock. After one thread gets the lock, other threads will be in the .. well, "ready" state but they are not actively trying to get the monitor (actually the VM is making them "automaticall wait" till the lock is released).So you can distinguish between the two states in terms of threads behaviour.
[This message has been edited by mohit joshi (edited February 16, 2001).]
 
Rosemol Thanjappan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mohit ,
I am extreamly thankful to you for your time and effort.
Now I can understand the thread behaviour better.

For conclusion :
When notifyAll is called on an object ,all the waited threads in this objects waiting pool , directly goes to Ready state.In the Ready state they are competing to get the object lock. In future when they gets object lock they will get executed.

I don't know whether I have to trust or not RHE diagram.

Thanking you all once again.

Rosemol.
reply
    Bookmark Topic Watch Topic
  • New Topic