Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

InterruptedException

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I got a small doubt.
Does a thread stops its execution because of InterruptedException.
I will be happy if some one clear this doubt.
thanks in advance
usman
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mohammad,
I wrote a small program to demonstrates how InterruptedException affects a thread. Since the program is self-documented, I don't want to deliberate too much on the details.
Just remember that when a running thread is interrupted, the catch/finally part of the exception handler is excecuted. Then the thread goes to the ready state again. When it gets picked up by the scheduler, the execution will resumefrom the point where it had stopped.
You can observe this happening when you run the following program. After the InterruptedException is caught, the Tick counter will continue from where it had stopped instead of starting from zero again.

Here is the sample out on my machine. The results will be consistent, though the Tick at which the execution resumes might differ based on the processor.


Hope this gives you something to start with.
Ajith

[This message has been edited by Ajith Kallambella (edited July 26, 2000).]
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you say that the interrupted thread picks up where it left off, isn't that really just due to how you structure your try/catch block? Since your try/catch block is within your for loop, the next statement after the catch is the for loop test condition.
In other words, what you're seeing in this code is normal exception (try/catch) behavoir and nothing really specific to threads other than the fact that you're calling a thread-related exception.
Let me know if I'm missing something.
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ajith,
I tried the code u have given for InterruptDemo !
Believe me, all the time the execution goes thru
successfully and there is no exception...........
Wonder why this happens ???
It meekly prints Back to Main.... at the end of its
execution.
Can u please highlight more on the behaviour of your
code or threads in general ??
Praveen Zala
 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ajith's program shows that Thread doesn't stop because of
InterruptedException. It is the opposite. If the thread
is sleeping or waiting, InterruptedException causes the
thread to move to ready-to-run and then running states.
However, if the exception is not caught, the thread will
die as usual with other exceptions.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dab,
Actually when the interrupted thread becomes ready for running, if there are any other threads waiting to be run, they might get picked up. And after running the pending threads, the execution of the interrupted thread will start.
Here is the modified code where I am starting another thread. The ticker thread which blocks other threads is interrupted after starting another thread. Note that though the InterruptedException is caught, the Ticker thread will not start running immediately. The scheduler picks up the "Bing"er thread. After Binger completes, the Ticker will resume its execution with Ticks running from where had stopped.

Again, here is the output dump produced on my machine. As noted earlier, actual results may vary, but the behaviour should be consistent.

Praveen - perhaps you are running a faster machine than I am. Try increasing the loop count of the ticker and/or replicate the dummy loop in the main method. The intention here is to let the ticker run for a while before it gets interrupted so that we can observe the consecutive Ticks. Otherwise the ticker will always stop at 0 and the "Back in main method" always appears at the last.
Hope this helps,
Ajith
[This message has been edited by Ajith Kallambella (edited July 26, 2000).]
 
Ranch Hand
Posts: 477
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ajith: I can�t understand two lines of code from your program, could you explain this to me?
First:

// Allow the Ticker thread to run.
Thread.yield();

Why do you do this? Up to now I thought the yield method isn�t necessarily in this case. This has a relation between daemon and no daemon threads?


// Just a dummy loop so that we can let the Ticker
// thread run for a while.
for ( int i = 0 ; i < Integer.MAX_VALUE ; i++);

Could you explain me how this works? I am a bit confused...
Thanks Ajith, no more doubts.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Marcela,
I would really like you to try my code commenting one or both of these two lines. See what happens. I can surely explain why they are there, but I feel you will understand it much better if you "experience" it.
Ofcourse, you can always come back here if you get thrown overboard.
Goodluck,
Ajith
 
Marcela Blei
Ranch Hand
Posts: 477
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ajith: I tried it now, sorry I didn�t tried it first to my reply. Now I understand the for loop but when I commented the yield line, program behavior doesn�t changed. Could it be that you put the yield because the first thread has a higher priority that the second one, and that how the JVM attends the priority order is system dependent so, putting yield you enssure that the second thread �ll start in the middle of the execution of the first one?
Thanks for your reply and for the code you made, it is a large job...
[This message has been edited by Marcela Blei (edited July 26, 2000).]
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Marcela,
Yes. You are absolutely right.
The yield was to make sure the Ticker thread started immediately instead of allowing the execution of main thread to continue. And I put the for loop so that the Ticker thread runs for a while and we don't interrupt it immediately after it gets started( Ticker = 0 ). This also helps prove another important concept - "interrupt() is a better way of stopping a selfish thread than stop()".
Perhaps one can do without the for loop, but it is mostly going to be machine dependent. Since I was focussing more on establishing a consistent behavioural pattern, I didn't pay much attention to redundancies like this
Ajith

[This message has been edited by Ajith Kallambella (edited July 26, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ajith,
I too tried the same code. Very nice code to learn.
So what you meant to say is you want the main thread to be on ready stage and the mythread to be on running stage. For that you used both yield() ans for loop but either one is ok. I tried the same code just commenting the for loop and leving with yield, the main thread started just after Tick 0. Next time commented both yield and for loop and tried got the same result.
Is it b'cas of scheduler.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you omit the for loop and just retain the yield call, the Ticker thread gets preempted at the first loop( Tick = 0 ) and then the main thread resumes. This happens because all the three threads( the main thread, the Ticker thread and the Binger thread ) are of the same priority. I wanted the main thread to go to the pending pool and hence I bumped up the priority of the Ticker thread in the second code snippet that I posted.
Now, as Marcela pointed out, in the scenario where the Ticker thread is running with a higher priority, just the call to yield will do the job. Again, we have the dominant variable here which is the platform-dependent thread scheduler. Hence different people are experiencing different outputs with or without these statements.
( see how well I convince you )
Ajith
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ajith,
Thanks for your time. Actually I just had an idea about the interrupt method. Today got a chance to experience it. Now I got an inspiration to try some more code like this.
Could you pls. explain for me about the Deamon thread (which is another thread out there)
 
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ajith,
After running your excellent program I got impression about interrupt() function that it doesn�t always stop a running thread. The thread could catch the exception and continue running. Is that true? If it is true then what should I do in case:
Which may cause a running thread to stop the execution?
1. sleep
2. intrrupt()
Should I pick option '2' or not in exam?
Your help would be appreciated!
vivek
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vivek,
Yes, you should probably pick (2) ie., interrupt().
Remember, interrupt stops the execution of the thread. Though the word "stop" may not be very appropriate to use here since the thread will eventually continue to run, if there are other threads waiting to run, the scheduler can use this opportunity to run them.
In case of the sleep(), the thread is still running and hence if it is a selfish thread, there is no chance for the other threads to run. For the scheduler, a sleeping thread is as good as the running thread!!
Hope this helps,
Ajith
 
Vivek Shrivastava
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ajith,
I am really getting confuse with word "stop". what does it exactly mean for the exam point of view? because what i think is that all the following action will cause a thread to stop the execution?
1. sleep()
2. stop()
3. suspend()
4. yield()
5. interrupt()
5. method like waitforID() or waitforData()
6. blocked for io
7. thread with hiegher priority
8. wait()
9. when there is no user thread exists any more
am i missing something here?
ajith i know u can help me. your help would be appreciated.
vivek
[This message has been edited by Vivek Shrivastava (edited July 26, 2000).]
[This message has been edited by Vivek Shrivastava (edited July 26, 2000).]
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vivek,
I can understand the cause of confusion here( belive me it happened to me too! ).
"Stop" can means -
* Thread has done its job, and so is "dead"
* Thread has been moved from the running stage and is no longer
using the CPU
* The scheduler can use this opportunity to run any pending
threads( provided the scheduling policy permits that )
"Blocked" means thread is still running( using CPU ), but it
is not actively executing any code. The thread is waiting
for something to happen, probably a resource handle or a return
status from a method call. If the running thread is blocked, the
scheduler cannot pull it out and let other threads run.

Now if we look at your list, the following can stop a running
thread( either temporarily or permanently )
* suspend- temporary
* yield - temporary
* interrupt - temporary
* stop- permanent
* Normal completion of the thread.- permanent
* thread with higher priority( if the scheduler honors priority ) - temporary
* wait- temporary

The ones that block the execution
* method like waitforID() or waitforData()
* blocked for io

I have tried to answer your question. However, due to subtle differences in how these terms are interpreted, one can always contest my explanations. If that happens, I will be more than happy to elaborate more on such confusing issues.
Ajith
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is a state diagram( pardon the mess ) which hopefully will clarify the things.

Ajith
[This message has been edited by Ajith Kallambella (edited July 26, 2000).]
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've learned a lot reading this post but I don't fully understand the output.
1. My first question is regarding the first code you submitted:
When you call myThread.interrupt(), shoudn't the output
have been :

Tick..11
Caught InterruptedException
Back in main Method
Tick..12
why is it that in your output you got Tick..12 before
writing back in main . The interrupt was suppose to stop
the thread and totaly let main take over right?
2. My second question is simmilar:
Its regarding the second piece of code you submitted.
When you have Thread.yield();
That stops the main method and give control to the higher
priority thread myThread. Nothing should happend till that
higher priority thread is compeletly finished.
So the line after Thread.yield in the main method should not
happen until myThread (higher priority) has completely
finished. How can the program even get to
myThread.interrupt when thats command is comming from a
lower priority thread.
Thanks in advance
 
Kourosh Keshavarzi
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just thought I'd bring this up again?
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey ajit,
which system are you working on.
on a windows system it does not make much of a difference wheather you put Thread.yeild() or not because it is time sliced.
if you are working on a pre-emptive system then it might make a difference.
In windows Thread.sleep(1000) acts as though for 1000ms the thread has stopped and allows other threads to run.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you interrupt a thread, it may not stop immediately. The JVM sets an internal flag to indicate the thread has been interrupted and eventually the thread stops running.( Take a look at <code>Thread.interrupted()</code> method. ) That's why the Tick 12 appears and then the control comes back to main method.
Again, the behaviour depends largely on the scheduler.
girish, <code>sleep()</code> puts the running thread to sleep. It is not equivalent to the <code>yield()</code> method where the thread allows other threads to run. When a thread sleeps, it is still in the "running pool of threads" and waiting threads continue to wait!
Ajith
reply
    Bookmark Topic Watch Topic
  • New Topic