Monday, April 25, 2011

What is the Diffrence Between Notify & NotifyAll" method in the Object Class.


What is the Diffrence Between Notify & NotifyAll" method in the Object Class ?
 Ans:
'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

It is partly correct, notifyAll() will notify all the threads and after that all the threads will contest for the monitor lock. The thread that gets the monitor lock will start the work and the rest will be waiting for the monitor lock.
The above difference is pretty big as the threads waiting for monitor will not require a notify() call to start processing but will start processing as soon as they get the monitor lock.
If you take the thread dump and see the state of the threads (although getting this dump at the correct time is somewhat tough),
·  In case of notify() only one thread will get to the RUNNING state and other will be in WAIT state
·  In case of notifyAll() only one thread will get to the RUNNING state and other will be in BLOCKED state

How to throw exception in run() method of Runnable?


I want to know how to throw exception in run() method of interface Runnable. Since there is no throwable exception declared in run() method of interface Runnable in Java API specification.
Ans:
Why would you want to?
I can't see any advantage. Exiting the run method will end the thread. Exiting with an exception will do the same (for instance if you were to throw a RuntimeException).
If you want some other thread to be informed of the error then just pass a message as normal (call a method to alter some state and notify other threads).

Relation between Parent and Child thread in java


It is  possible that a parent thread dies before the child ones?
Explanation:
Say i have a Thread "Parent" in it i am starting another two threads say "child1" and "child2" then both childs are still in running phase and Parent Thread dies.
Ans:

All Threads are 'unrelated', there are no parent and child threads. So once the 'parent' thread kicks off 'child1' and 'child2', then the three threads are independent. They can end in any order and they don't affect the running of other threads. Which means 'parent' can die before 'child1' and 'child2'.

There are some modifications to this. For example, if 'parent' is the last non-daemon thread running (and thus 'child1' and child2' threads are daemon threads), then when 'parent' dies, the JVM starts to shutdown, so the 'child' threads would also die. The last modification would be if you have some synchronizing code that prevents 'parent' from dieing until the 'child' threads die, or that signals the 'child' threads to die when the 'parent' does.