How to use wait and notify - java

I am creating a java application in which I am using three threads to perform three operations on a text file simultaneously.I have a toggle button in my application when I click start i am calling a method call() in which i am creating and starting all these threads and when i click stop i am calling a new method stopcall() in which i write a code to stop all these thread.
public void stopcall() throws Exception {
System.out.println("hello stop call");
synchronized(t) {
t.wait();
}
synchronized(t1) {
t1.wait();
}
synchronized(t2) {
t2.wait();
}
}
But stopcall() method is not working properly whenever i am calling this method my application hanged.I would be grateful if somebody help me and tell me how to use wait and notify in my application

Your application hangs because you are waiting for a locked object.
wait() method hangs the thread until another thread uses notify() on that object.

You have to synchronize the method that accessing the shared object (the file in this case) to enable safe threading. here is an example using a boolean flag to indicate if the resource is currently in use or not.
if in use, the next thread will invoke wait() and will wait for a notification.
meantime when the 'currently using' thread will finish the synchronized block - it will invoke notifyAll() to alert all the waiting threads that the resource is free.
public class TestSync {
private boolean fileInUse = false;
public synchronized void syncWriting() {
// blocks until a the file is free. if not - the thread will 'wait'.
// when notified : will do the while-loop again
while (true) {
if (!fileInUse){
System.out.println("using the free file");
fileInUse = true;
//
// code to write and close the file
//
notifyAll();
return;
}
try {
// wait if file in use. after being notified :
wait();
} catch (InterruptedException e) {e.getMessage();}
}
}

The wait()/notify()/notifyAll() methods are fairly easy to understand.
foo.wait() releases the lock on foo, and then it sleeps until foo is notified, and then in reacquires the lock before it returns.
foo.notifyAll() wakes up all threads that are sleeping in foo.wait() calls. If no threads are sleeping at the moment when it is called, then it does not do anything at all.
foo.notify() is the same as foo.notifyAll() except, it only picks one sleeping thread (if any) and wakes it.
The trick to using wait() and notify() is, suppose that you expect some thread A to wake up thread B with a foo.notify(). How do you guarantee that thread B will already be sleeping in a foo.wait() call before thread A calls foo.notify()?
Remember: If the notify happens first, then it will be "lost". That is, the notify will do nothing, and the wait will never return.
That brings us to the reason why foo.wait() and foo.notify() are only allowed to be called from inside a synchronized(foo) block. You are supposed to use the synchronization, and some shared variable to prevent thread A from wait()ing for a notification that already has happened.

Related

Awake thread from sleep

I am creating an program and working with threads in details for the first time and stuck into an situation .Please help me in that.
I am having a thread which is in wait state.Now at some instance I want to kill or to awake thread and resume from another class .For this I am saving object of thread .I don't know how to do this .I tried to notify thread but got exception.Here is my code:
Class one:
Thread t= new Thread(new Runnable() {
#Override
public void run() {
try{
Thread.sleep(VariableClass.THREAD_WAIT_SECONDS);
if(message !=null)
message_status = message.getStatus();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
//do other stuff and save the thread object
VariableClass.threads.remove(message.getUniqueId());
}
});
t.start();
VariableClass.threads.put(pojo.getUniqueId(),t);
Class two:
Thread t =VariableClass.threads.get(tempId);
t.notify();
I just want to resume or kill thread.
If your thread t is sleeping, calling t.interrupt() will cause an InterruptedException to be thrown from the line calling Thread#sleep. It will get caught in your catch block and your thread will proceed from there to do its cleanup and exit.
If there was an issue where your thread was not sleeping or waiting but still wanted to be aware of whether it was interrupted, the code in your Runnable could check the interrupted flag on the current thread. Remember that the interrupted flag gets reset once an InterruptedException is thrown.
Wait and notify are for threads that are synchronizing on a monitor, that's not applicable to your example. Threads wait on a monitor and receive notifications, but the notifications are not made to a specific thread; for Object#notify, some thread waiting on that monitor gets chosen but the thread calling notify has no control over which one is picked.
Here's an example of using interrupt to wake a thread from sleeping.
Your thread is sleeping for the specified amount of time. Call interrupt on it, if you just want to "kill it" and you don't care too much what will happen with it later. You cannot simply "awake it" from another thread, if it's sleeping it has to sleep as much as it has been told to. Calling notify has nothing to do with this situation (there's no prior wait call). Even if did, you're calling it incorrectly.
You do not use notify in this case. I suggest reading the JavaDoc on #wait/#notify/#notifyAll
You use #notify and #notifyAll to create a framework with concurrency such as a Thread that does work on an instance of a certain object and other threads are waiting to work on it.
A thread "dies" out if the run function is over, but if you want to stop the thread immediately, use #interrupt.

Does the waiting thread revisit the code inside synchronized method

I was reading about thread synchronisation and wait/notify constructs from the tutorial. It states that
When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll, informing all threads waiting on that lock that something important has happened.
Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of wait.
AFAIK, if there are multiple threads which can compete for the lock when the first thread is awaken by the notify, any one of them can get to own the lock on that object. My question is, if this first thread itself re-acquires the lock, does it have to start all over from the beginning of the synchronized method (which means, it again executes the code before the while loop checking wait() condition) or does it just pause at the wait() line?
// Does the waiting thread come back here while trying to own the
// lock (competing with others)?
public synchronized notifyJoy() {
// Some code => Does this piece of code gets executed again then in case
// waiting thread restarts its execution from the method after it is notified?
while (!joy) {
try {
// Does the waiting thread stay here while trying to re-acquire
// the lock?
wait();
} catch(InterruptedException e) {}
}
// Some other code
}
A method only gets exited when the thread executing it finishes executing its run method, whether by returning normally or having an exception be thrown that goes uncaught within that run method. The only way for your method to not get executed until one of those things above happens is for the JVM to be killed out from under you (with java.lang.System.exit, killing the java process with kill -9, etc.), or if the method is being run in a daemon thread where the JVM is shutting down. There's nothing weird going on here. The thread that waits gives up the lock and goes dormant, but it doesn't somehow leave off executing the method.
The thread awakened from its call to wait never went anywhere; the whole time that the thread was waiting it was still in the wait method. Before it can leave the wait method it first has to acquire the lock that it gave up in order to start waiting. Then it needs to retest whatever condition it needs to check before it can know whether to keep on waiting.
This is why the guarded blocks tutorial tells you that waits have to be done in a loop:
The invocation of wait does not return until another thread has issued a notification that some special event may have occurred — though not necessarily the event this thread is waiting for:
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
(The wording used by the tutorial is misleading; the word "interrupt" should be "notification". Also it is unfortunate that the tutorial code shown eats the InterruptedException without setting the interrupt flag, it would be better to let the InterruptedException be thrown from this method and not catch it at all.)
If the thread did "start over" then this loop wouldn't be required; your code would start at the beginning of the method, acquire the lock, and test the condition being waited on.
Thread execution starts directly after the call to wait. It does not restart the block from the beginning. wait() can be roughly implemented similar to
public void wait() {
release_monitor();
wait_monitor();
acquire_monitor();
}
This is no where near how it is actually implemented, it is just a rough idea of what goes on behind the scenes. Each Object has a monitor associated with it that can acquired and released. Only one thread can hold the monitor at a time and a thread can acquire a monitor recursively with no issue. A call to wait on an Object releases the monitor allowing another thread to acquire it. The waiting thread then waits until it is woken up by a call to notify/notifyAll. Upon being woken up the waiting thread waits again to require the Object's monitor and returns to the calling code.
Example:
private Object LOCK = new Object;
private int num = 0;
public int get() {
synchronized( LOCK ) {
System.out.println( "Entering get block." );
LOCK.wait();
return num;
}
}
public void set( int num ) {
synchronized( LOCK ) {
System.out.println( "Entering set block." );
this.num = num;
LOCK.notify();
}
}
"Entering get block." will only be printed once for each call to get()

is this the correct way to 'stop' a thread gracefully?

instead of continuous checking of variable inside a loop:
class Tester {
public static void main() {
Try t = new Try();
Thread.sleep(10); //wait for 10 milliseconds
t.interrupt(); // 'interrupt' i.e stop the thread
}
}
public class Try extends Thread {
public void interrupt() {
//perform all cleanup code here
this.stop();
/*stop() is unsafe .but if we peform all cleanup code above it should be okay ???. since thread is calling stop itself?? */
}
}
In order to perform interrupt in a good manner you should poll for the "interrupted()" method inside the thread that is being interrupted.
Just be aware that calling interrupted() method resets the interruption flag (that is set when calling interrupt()).
I guess the bottom line is that you have to continuously poll inside the thread in order to perform a graceful interruption.
You should never ever call .stop() on a Thread, period. It's not enough for the thread to perform its own cleanup. Since calling .stop() immediately releases all monitors, other threads may see shared data in an inconsistent state which may result in almost impossible to track errors.
Use Thread.interrupt() method instead of Thread.stop(). In the interrupted thread you can catch the InterruptedException and do any cleanup required.
A similar questions has already been asked here, you can find a code sample there too.

Difference between WAIT and BLOCKED thread states

What is the difference between thread state WAIT and thread state BLOCKED?
The Thread.State documentation:
Blocked
A thread that is blocked waiting for a monitor lock is in this state.
Waiting
A thread that is waiting indefinitely for another thread to perform a particular action is in this state
does not explain the difference to me.
A thread goes to wait state once it calls wait() on an Object. This is called Waiting State. Once a thread reaches waiting state, it will need to wait till some other thread calls notify() or notifyAll() on the object.
Once this thread is notified, it will not be runnable. It might be that other threads are also notified (using notifyAll()) or the first thread has not finished his work, so it is still blocked till it gets its chance. This is called Blocked State. A Blocked state will occur whenever a thread tries to acquire lock on object and some other thread is already holding the lock.
Once other threads have left and its this thread chance, it moves to Runnable state after that it is eligible pick up work based on JVM threading mechanism and moves to run state.
The difference is relatively simple.
In the BLOCKED state, a thread is about to enter a synchronized block, but there is another thread currently running inside a synchronized block on the same object. The first thread must then wait for the second thread to exit its block.
In the WAITING state, a thread is waiting for a signal from another thread. This happens typically by calling Object.wait(), or Thread.join(). The thread will then remain in this state until another thread calls Object.notify(), or dies.
The important difference between the blocked and wait states is the impact on the scheduler. A thread in a blocked state is contending for a lock; that thread still counts as something the scheduler needs to service, possibly getting factored into the scheduler's decisions about how much time to give running threads (so that it can give the threads blocking on the lock a chance).
Once a thread is in the wait state the stress it puts on the system is minimized, and the scheduler doesn't have to worry about it. It goes dormant until it receives a notification. Except for the fact that it keeps an OS thread occupied it is entirely out of play.
This is why using notifyAll is less than ideal, it causes a bunch of threads that were previously happily dormant putting no load on the system to get woken up, where most of them will block until they can acquire the lock, find the condition they are waiting for is not true, and go back to waiting. It would be preferable to notify only those threads that have a chance of making progress.
(Using ReentrantLock instead of intrinsic locks allows you to have multiple conditions for one lock, so that you can make sure the notified thread is one that's waiting on a particular condition, avoiding the lost-notification bug in the case of a thread getting notified for something it can't act on.)
Simplified perspective for interpreting thread dumps:
WAIT - I'm waiting to be given some work, so I'm idle right now.
BLOCKED - I'm busy trying to get work done but another thread is standing in my way, so I'm idle right now.
RUNNABLE...(Native Method) - I called out to RUN some native code (which hasn't finished yet) so as far as the JVM is concerned, you're RUNNABLE and it can't give any further information. A common example would be a native socket listener method coded in C which is actually waiting for any traffic to arrive, so I'm idle right now. In that situation, this is can be seen as a special kind of WAIT as we're not actually RUNNING (no CPU burn) at all but you'd have to use an OS thread dump rather than a Java thread dump to see it.
Blocked- Your thread is in runnable state of thread life cycle and trying to obtain object lock.
Wait- Your thread is in waiting state of thread life cycle and waiting for notify signal to come in runnable state of thread.
see this example:
demonstration of thread states.
/*NEW- thread object created, but not started.
RUNNABLE- thread is executing.
BLOCKED- waiting for monitor after calling wait() method.
WAITING- when wait() if called & waiting for notify() to be called.
Also when join() is called.
TIMED_WAITING- when below methods are called:
Thread.sleep
Object.wait with timeout
Thread.join with timeout
TERMINATED- thread returned from run() method.*/
public class ThreadBlockingState{
public static void main(String[] args) throws InterruptedException {
Object obj= new Object();
Object obj2 = new Object();
Thread3 t3 = new Thread3(obj,obj2);
Thread.sleep(1000);
System.out.println("nm:"+t3.getName()+",state:"+t3.getState().toString()+
",when Wait() is called & waiting for notify() to be called.");
Thread4 t4 = new Thread4(obj,obj2);
Thread.sleep(3000);
System.out.println("nm:"+t3.getName()+",state:"+t3.getState().toString()+",After calling Wait() & waiting for monitor of obj2.");
System.out.println("nm:"+t4.getName()+",state:"+t4.getState().toString()+",when sleep() is called.");
}
}
class Thread3 extends Thread{
Object obj,obj2;
int cnt;
Thread3(Object obj,Object obj2){
this.obj = obj;
this.obj2 = obj2;
this.start();
}
#Override
public void run() {
super.run();
synchronized (obj) {
try {
System.out.println("nm:"+this.getName()+",state:"+this.getState().toString()+",Before Wait().");
obj.wait();
System.out.println("nm:"+this.getName()+",state:"+this.getState().toString()+",After Wait().");
synchronized (obj2) {
cnt++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Thread4 extends Thread{
Object obj,obj2;
Thread4(Object obj,Object obj2){
this.obj = obj;
this.obj2 = obj2;
this.start();
}
#Override
public void run() {
super.run();
synchronized (obj) {
System.out.println("nm:"+this.getName()+",state:"+this.getState().toString()+",Before notify().");
obj.notify();
System.out.println("nm:"+this.getName()+",state:"+this.getState().toString()+",After notify().");
}
synchronized (obj2) {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Java sync games: synchronized && wait && notify

I'm coming from .NET world, and unfortunately looking Java source with .NET's eyes.
Following code is from Android Apps (though not Android specific at all):
private class Worker implements Runnable {
private final Object mLock = new Object();
private Looper mLooper;
Worker(String name) {
Thread t = new Thread(null, this, name);
t.start();
synchronized (mLock) {
while (mLooper == null) {
try {
mLock.wait();
} catch (InterruptedException ex) {
}
}
}
}
public Looper getLooper() {
return mLooper;
}
public void run() {
synchronized (mLock) {
Looper.prepare();
mLooper = Looper.myLooper();
mLock.notifyAll();
}
Looper.loop();
}
public void quit() {
mLooper.quit();
}
}
I'm not precisely clear with how synchronized works.
First I thought that synchronized is locking mLock object, but then if after t.start() constructor thread enters sync block first, it would block it at mLock.wait(), and implicitly block thread "t" by blocking it from entering synchronized block.
This is obviously wrong, because my phone rings as supposed :)
Next thought is that synchronize synchronizes "code block" (in which case, there two synchronized block are independent => threads can enter two different sync block at same time without restriction), and that fitted perfectly...
... until my colleague told me that mLock.wait() releases lock on mLock and enables other thread to enter critical section on mLock in same time.
I'm not sure if I was clear enough, so will gladly answer any further questions on this.
Check out the javadoc on Object.wait(). It's "magic" in that it drops the monitor that was acquired when entering the synchronized {} block. That allows another thread to acquire the monitor and call Object.notify().
When another thread calls notify() to wake the waiting thread from its wait() call, the waiting thread must re-acquire the monitor and will block until it can -- the monitor is only dropped for the duration of the wait() call. And the notifying thread completes its synchronized block before the newly-awoken waiting thread can proceed. Everything is sequenced predictably.
synchronized uses object monitors. Calling wait() on the object atomically releases the object monitor (for otherwise no other thread could ever take the monitor and issue a notify to the waiter(s)).
Yes. If you read the description of the wait() method, you'll learn that it causes the thread to release the lock and block until another thread invokes notify or notifyAll on the lock. The current thread waits until it can re-acquire the lock, and once it does, it continues execution.
The code shown follows poor practice, however, because it "publishes" (that is, it makes the object accessible to other threads) the Worker instance before it is fully constructed. The use of additional barriers in this method, combined with the private nature of the class, probably make this case safe, but in general, it is not.
Let me explain:
The constructor launches a new thread that will execute the run() method.
This new thread will obtain a new Looper object, store it in the mLooper field and then run the Looper message loop. In between it will notify() the first thread that mLooper has been set.
The first thread will therefore return from the constructor only after mLooper has been set which means that processing of Looper.loop(), by the 2nd thread, is bound to start shortly/has already started.

Categories

Resources