I have one question regarding wait/notify based threads interaction.
The output of the below code is Im. How output can be Im as there is no other thread calling notify() on Thread object. Is it like JVM implicitly calls notify() in above such scenarios where you try to wait on Thread class instance.
A thread operation gets stuck when it waits without receiving any notification. Now what if I wait on Thread class instance wait(). For e.g.
public class WaitingThread {
public static void main(String[] args) {
Thread t1 = new Thread();
t1.start();
synchronized (t1) {
try {
t1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Im");
}
}
Your program is leaving wait() because the thread is finishing immediately. This is a byproduct of the Thread library that the Thread object is notified when the thread finishes. This is how join() works but it is not behavior that should be relied on since it is internal to the thread sub-system.
If you are trying to wait for the thread to finish then you should be using the t1.join() method instead.
Your thread is finishing immediately because it does not have a run() method defined so it is started and finishes. Really it is a race condition and the thread that is started could finish before the main thread gets to the wait() method call. You can see this if you put a short sleep (maybe 10ms) after the start() is called. Then you can see that you program will sit in wait() forever.
Related
I want to know how and when does a Thread move back and forth between runnable and running states.What actually happens behind the scenes.I guess this will be needed in case of ThreadPool but I am not able to understand entirely.Please help me to understand this.
if thread is in running state that means its executing run() method and when its in runnable method its executing start() method....so I guess moving from running to runnable means its going back from run() to start()
In the nomenclature of most operating systems, "running" means that the thread actually is executing instructions on some CPU, and "runnable" means that nothing prevents the thread from "running" except the availability of a CPU to run on.
A Java program can not tell the difference between those two states. The thread states that Java knows about are NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.
A thread is NEW before t.start() is called, and it can never go back to NEW afterward. WAITING and TIMED_WAITING both mean that the thread is waiting for a notify() call in some other thread. BLOCKED means it is waiting for anything else (e.g., to enter a synchronized block), and TERMINATED means it's finished.
Yield is a static method that tells the currently executing thread to give a chance to the threads that have equal priority in the Thread Pool.
There is no guarantee that Yield will make the currently executing thread to runnable state immediately. Remember an important point that yield method does not make the thread to go to Wait or Blocked state. It can only make a thread from Running State to Runnable State.
Extract from A Programmer's Guide to Java SCJP Certification: Threads:
static void yield()
This method causes the current thread to temporarily pause its execution and, thereby, allow other threads to execute. It is up to the JVM to decide if and when this transition will take place.
static void sleep (long millisec) throws InterruptedException
The current thread sleeps for the specified time before it becomes eligible for running again.
final void join() throws InterruptedException
final void join(long millisec) throws InterruptedException
A call to any of these two methods invoked on a thread will wait and not return until either the thread has completed or it is timed out after the specified time, respectively.
void interrupt()
The method interrupts the thread on which it is invoked. In the Waiting-for-notification, Sleeping, or Blocked-for-join-completion states, the thread will receive an InterruptedException.
Below Example illustrates transitions between thread states. A thread at (1) sleeps a little at (2) and then does some computation in a loop at (3), after which the thread terminates. The main() method monitors the thread in a loop at (4), printing the thread state returned by the getState() method. The output shows that the thread goes through the RUNNABLE state when the run() method starts to execute and then transits to the TIMED_WAITING state to sleep. On waking up, it computes the loop in the RUNNABLE state, and transits to the TERMINATED state when the run() method finishes.
Example :Thread States
public class ThreadStates {
private static Thread t1 = new Thread("T1") { // (1)
public void run() {
try {
sleep(2); // (2)
for(int i = 10000; i > 0; i--); // (3)
} catch (InterruptedException ie){
ie.printStackTrace();
}
}
};
public static void main(String[] args) {
t1.start();
while(true) { // (4)
Thread.State state = t1.getState();
System.out.println(state);
if (state == Thread.State.TERMINATED) break;
}
}
}
Possible output from the program:
RUNNABLE
TIMED_WAITING
...
TIMED_WAITING
RUNNABLE
...
RUNNABLE
TERMINATED
I am reading Java Threads. I am looking into sleep() method. The books states that
When a thread encounters a sleep call, it must go to sleep for
specified amount of time, unless it is interrupted before its wake-up
time.
I am reading about interrupts, but how can a thread send interrupt to itself? I think so
another thread can send interrupt? Am i understanding correct? Additionally, do both of
the threads, one which will send the interrupt should be having same target Runnable? If
for suppose a thread is interrupted, does it go back to Runnable state? I am really sorry,
if i am sounding stupid, it's just pretty new for me. Thanks
A Thread can't interrupt itself while sleeping, because it is... sleeping.
A picture is worth a thousand words so here is a simple example where a thread starts sleeping and the main thread interrupts it:
public static void main(String[] args) throws Exception {
Runnable sleeper = new Runnable() {
public void run() {
try {
System.out.println("sleeper is going to sleep");
Thread.sleep(1000);
System.out.println("sleeper is awake");
} catch (InterruptedException e) {
System.out.println("sleeper got interrupted");
}
}
};
Thread t = new Thread(sleeper);
t.start(); //run sleeper in its own thread
Thread.sleep(500); //sleeping in main a little to make sure t is started
t.interrupt();
}
which prints:
sleeper is going to sleep
sleeper got interrupted
As for the main question - Sleeping thread cannot interrupt itself because it sleeps, BUT any other thread can try to iterrupt the sleeping one. Here you have doc explaining threads and thread lifecycle.
Yes, only another thread can send an interrupt to a sleeping thread. It is not possible for a thread to send interrupt to itself(Simply contrast it to real life, if a person is sleeping then to wake him, we require some other person). And yes, after interrupting a thread goes back to Runnable state.
As far as I know its another thread which causes the interrupt. So when a thread calls sleep for certain time, Java Runtime makes a note of this, and when time has passed, it causes the interrupt which wakes up the sleeping thread.
According to Thread#interrupt
Thread can interrupt itself.It is always possible.
Example is :
public static void main(String[] args) throws ParseException, InterruptedException {
Thread.currentThread().interrupt();
try{
Thread.currentThread().sleep(200);
}catch(InterruptedException ie){
System.out.println("Current thread is interrupted");
}
}
invoking interrupt never throws exception.It set the interrupt status flag.
When this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
or
The following code is in the SCJP6 book
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
}
Won't the previous code cause a deadlock as both thread a and b have a lock on b (in the respective synchronized blocks)?
I am missing something, but not quite sure what it is.
The likeliest execution is as follows:
there is a slight delay between b.start() and the run method being executed
the main thread therefore manages to acquire the lock on b and enters the synchronized block
it then waits on b (which releases the lock)
when run starts executing, the monitor is available (or will be available fairly shortly) so it can enter the synchronized block
when it's done it notifies b that it can stop waiting
the main thread completes.
However, depending on thread scheduling, it is not impossible that run be executed first, in which case the main thread could wait forever on b.wait(). For example, if you help that situation by inserting a small Thread.sleep(100) right after b.start(), you should observe that behaviour.
Bottom line: it is a smelly code that could encounter liveness issues (it is not a deadlock per se since the lock is available).
It depends.
From the documentation of wait method -
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases
ownership of this monitor and waits until another thread notifies
threads waiting on this object's monitor to wake up either through a
call to the notify method or the notifyAll method. The thread then
waits until it can re-obtain ownership of the monitor and resumes
execution.
So, if you consider the two scenarios -
If ThreadA gets the lock on object b first, it will wait, resulting in the release of the lock, which will cause ThreadB to continue with its work.
If ThreadB gets the lock first, well, it will continue it's work, release the lock, and then ThreadA will start. Next, ThreadA will wait on the object lock b, which may cause it to wait forever.
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();
}
}
}
}
all i want block of code wait for another thread to die
where this thread not event thread
I believe this is what Thread.join() method is for:
public final void join() throws InterruptedException
Waits for this thread to die.
From what I've been able to understand, it looks like you want a block of code to be executed after some thread dies, but you don't want Thread.join() to block the current thread? Then execute the whole thing in a yet another thread:
new Thread() {
public void run() {
someThread.join(); // someThread is the thread that you're waiting to die
// your block of code
}
}.start();
This will execute the code after someThread dies, but won't suspend the current thread.
java.util.concurrent.CountDownLatch can be used here.