Interrupting a thread

consider the following program
class A extends Thread {
public void run() {
try {
synchronized (this) {
wait();
} catch (InterruptedException ie) {
System.out.println("isInterrupted() inside catch is " + isInterrupted());
public static void main(String[] args) {
A a1 = new A();
a1.start();
a1.interrupt();
System.out.println("a1.isInterrupted() inside main is " + a1.isInterrupted());
one of the output for this program is :
a1.isInterrupted() inside main is true
a1.isInterrupted() inside catch is false
why is this an output. As for the specification of thread method isInterrupted() method never resets the Interrupt flag of a thread.

public static boolean interrupted()
Tests whether the current thread has been interrupted.
The interrupted status of the thread is cleared by this method.
In other words, if this method were to be called twice in succession,
the second call would return false
(unless the current thread were interrupted again,
after the first call had cleared its interrupted status
and before the second call had examined it).
*/

Similar Messages

  • Interrupting a Thread in a Remote Object?

    HI,
    I am trying to get some thread synchronization to happen between a client and a remote RMI object. Essentially what I am trying to accomplish, is that if I interrupt a call on a blocking method in the remote object, I want the thread to throw the InterruptException. For example, the following code represents what I am trying to accomplish:
    package bca.test.rmi;
    import java.rmi.Naming;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class InterruptThreadApp {
    RemoteBlockingObjectInt remote = null;
    public static void main(String[] args) throws Exception {
    //Create the remote object
    RemoteBlockingObject obj = new RemoteBlockingObject();
    //bind it to the registry
    Naming.rebind("rmi://localhost/blocking", obj);
    //start the client, or the thread which will access the blocking call remotely
    InterruptThreadApp app = new InterruptThreadApp();
    Thread blocking = null;
    //wait for the thread to start
    synchronized ( app ) {
    blocking = app.startClient();
    app.wait();
    Thread.sleep(2000);
    //now interrupt the thread (note: the remote object should be blocking in
    //the blockingMethod().. this should produce an InterruptException?
    blocking.interrupt();
    public Thread startClient() {
    Thread t = new Thread("Client") {
    public void run() {
    try {
    //get a handle to the stub
    remote = (RemoteBlockingObjectInt) Naming.lookup("rmi://localhost/blocking");
    //now make a call to the blocking method, but first wake up the client
    synchronized ( InterruptThreadApp.this ) {
    InterruptThreadApp.this.notify();
    //now make the blocking call
    remote.blockingMethod();
    catch (InterruptedException e) {
    System.out.println("WooHoo! This is what we want! But it never gets thrown :(");
    catch (Exception e) {
    e.printStackTrace();
    t.start();
    return t;
    package bca.test.rmi;
    import java.rmi.server.UnicastRemoteObject;
    import java.rmi.RemoteException;
    import java.rmi.Remote;
    public class RemoteBlockingObject extends UnicastRemoteObject implements RemoteBlockingObjectInt {
    Object obj = new Object();
    public RemoteBlockingObject() throws RemoteException {
    super();
    public void blockingMethod() throws RemoteException, InterruptedException {
    synchronized (obj) {
    System.out.println("About to block.. so we can be interrupted later");
    obj.wait();
    interface RemoteBlockingObjectInt extends Remote {
    public void blockingMethod() throws RemoteException, InterruptedException;
    When I make a call to "remote.blockingMethod()", it blocks in the remote object (buy just "wait" ing). I want to interrupt this thread, by issuing an Thread.interrupt(). When I do so (I call "blocking.interrupt()"), nothing happens... no exception is thrown.. it just silently fails.
    Ok, so I suppose that we can not interrupt a remote thread.. that is fine. But what if I want to interrupt the RMI thread making the remote call? I don't want it to block forever. How can I "cancel" the remote call?
    Ideally, I would like the remote.blockingMethod() call to throw an InterruptException when I issue an "interrupt()" on the blocking thread. Any suggestions on how I might accomplish this?
    Thanks,
    Bryan

    While you can interrupt the RMI call, you cannot stop the active processing. That is, you cannot force a thread to stop (see the Java API documentation on Thread.stop().)
    Since the Client RMI call is a waiting thread, you need another Client thread to do a secondary RMI call. The trick is to have the new RMI endpoint connection thread on the RMI Server interrupt the original RMI endpoint connection thread.
    The only way you can interrupt an RMI call is to have the endpoint connection thread that runs on the RMI Server be aware that the user may wish to interrupt it.
    The best means of interruption is for the endpoint connection thread to use "worker threads". The endpoint connection thread waits for the workers to finish and is interruptible by both the workers and other endpoint connection threads.
    Another means of interruption is for the endpoint connection thread to segment the task into units of work and check for an interruption between those units of work.
    There are two ways I've done RMI call interruption.
    One is for the Client to pass a unique id (UID -- that uniquely identifies the request) to the Server with the original call. When the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread.
    The major problem with this is the unique id. It absolutely, positively must be unique. Otherwise you run the risk of Client_A purging Client_B's request.
    The second method requires callback. If your Client is behind a firewall then RMI callback is near impossible. In such a case you must come up with a way for the Server to call the Client that is secure (the firewall problem.)
    The Client must export a remote object and pass that remote object to the Server with the original call.
    The endpoint connection thread recognizes the remote object and does a call back to the Client passing information that uniquely identifies itself (UID). Since the Server generates the UID, it can guarantee uniqueness.
    The Client callback implementation runs as a separate thread since the Client is in fact an RMI Server itself (when it did the export.) The Client must save the UID. The Client must start a new thread for the interrupt procedure or inform a waiting thread that the Server called back.
    Just like method one, above, when the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread. Simple.
    For an academic example using call back go over to Jini.org. They have an example called "Cancellation" at:
    http://starterkit-examples.jini.org/
    For a professional, open source implementation of both these methods go over to CoopSoft.com. The Tymeac (Java) projects support canceling both waiting and autonomous requests at:
    http://www.coopsoft.com/JavaProduct.html

  • Timer that will interrupt a thread

    How do I create a timer that will interrupt a thread?
    I need to put this timer inside the thread, and I should be able to manipulate the time.
    I have managed to create an inner class that act as the timer. But, I can't make the timer to interrupt the main thread.
    Can anyone help me? Is there any simpler way to do this?

    See Thread.interrupt()
    If you call this while a thread has called sleep() and is waiting, this should then throw an InterruptedException
    BTW, in the case where you have a thread that reading from a socket / inputstream, and blocked on read(), the way that I always use to unblock my thread is to simply close the stream, which generates an IOException and unblocks the thread.
    ...And BTW Thread.stop() has never been implemented and does nothing!
    Edited by: tjacobs01 on Jan 3, 2008 6:09 AM

  • Interrupting Main Thread

    Hi,
    Is there a way to interrupt a Thread.sleep() (ie the main Thread executing)
    I was also wondering if when you call Thread.enumerate() if
    it returns an array of all the new threads which have been created and still exist at that point in time ?
    The reason is, sometimes after a period of time after my application has been running, and 'rdate' will happen on the system and if the time is set backwards, any Threads currently sleeping do not wake up and need to be interrupted.

    Did you look at the API docs?
    Thread.interrupt() will interrupt a Thread. You could
    keep a reference to all your sleeping threads and call
    interrupt() on each one when you want. This will
    interrupt them from their "sleep" and throw an
    InterruptedException.
    http://java.sun.com/j2se/1.3/docs/api/java/lang/Thread.
    tml
    http://java.sun.com/j2se/1.3/docs/api/java/lang/Interru
    tedException.htmlYes, I do understand how interrupt will interrupt a thread from a sleep. I should rephrase the question - There are currently a number of threads executing (there are over 2000 classes). This particular class does not know anything about the threads executing and their current state. When the system time is changed (by an rdate (unix)) this class is notified by a C program (which calls the rdate). Any threads in a sleep at this current time will come out of the sleep because time has gone backwards - so now the currentTimeMillies is returning a value less than the time it started the sleep with. Now ... I need to interrupt all of the threads which are currently sleeping - which this class does not have a handle to, it is only for being notified when an 'rdate' happens. I have worked out, I can use Thread.enumerate(Thread [] threads) to get a handle to all of the current threads. I can interrupt all of the threads by looping through this array. What I was asking is ... If a class uses a Thread.sleep - so it is telling the main thread to sleep - how do I interrupt it (I have worked out the enumerate() call will even return the AWT thread, so I assume I can interrupt it)
    Now another problem is, the interrupt will not interrupt threads which are currently in a wait() state.

  • How to stop/kill/interrupt a thread stuck on reflection method invoke

    Hi all,
    I have a thread that loads some class using reflection and invokes a method in it.
    I want to be able to stop that thread if needed by the user.
    For some reason, interrupt on that thread doesn't do anything - thread is still inside the invoke call.
    Is there any way to stop it?

    The only really safe way to have isolated code is to a seperate process you can kill.
    I wouldn't suggest using Thread.stop unless you have to, but that may be the case here. Stopping the thread this way might be worse than just discarding the Thread and moving on. (depending on what it is doing) i.e. another option is to ignore the thread and hope it doesn't matter. ;)
    However, before you do that I suggest you call Thread.getStackTrace() and log it. This can be useful in diagnosing WHY your thread needed to be kill and possibly give you a chance to fix it next time.

  • Interrupting a Thread thats blocking for I/O

    OK, here is the problem. I need to interrrupt a thread that is blocking on I/O. The run method of my thread looks something like this...
    run(){
    while(connected){
    try{
    recieved = in.readLine();
    // do something with recieved data
    } catch(InterruptedIOException e){
    // do something
    } catch(SocketException e){
    // do something else
    } catch(IOException e){
    // do some more of something else
    I also have a fuction like this...
    private void stop(){
    connected = false;
    myThread.interrupt();
    None of this appears to be working. The interrup method runs but no exceptions are thrown. I need to be able to tell the thread to stop blocking for I/O an stop running. Is there some other way, or am I on the right track and its just coded wrong? Any help would be great.

    There are 2 reasons for your code to mallfunction:
    1. You should catch an InterruptedException first (this is thrown at Thread.interrupt()), not InterruptedIOException (which comes from the Socket).
    2. For ensuring your thread.stop, you have messed up 2 different techniques:
    Setting the connected = false in your stop method could make you jump out your whole while loop, so you will never reach you code in the catch blocks.
    You also call myThread.interrupt() so if you stop() method occurs in the middle of processing, you will end-up in you catch(InterruptedException) block.
    So there are 2 distinct reactions that may occur at your stop(), depending on them moment when it is called, which doesn't look so good.
    Depending on how you want your code to behave (to end-up in the catch block or after the whole while loop) use just one of the instructions in your stop() method. It is recomended that you keep 'connected = false', but then you have to watch out the blocking IORead :(

  • Can anyone introduce me a tutorial on  "yield" and  "interrupt" of Thread?

    Hello, everyone!
    I am learning JAVA Thread. I have read all the parts of section "Threads: Doing Two or More Tasks at Once (Essential Java Classes) " of the tutorial "The JAVA Toturial" on java.sun.com but failed to find anything about the usage of functions "yield" and "interrupt".
    Can anyone introduce me some tutorials or simple source codes dealing with the usage of the two functions?
    Thanks in advance,
    George

    yield is used when you want to let another thread run. Its particularly useless as the scheduler will handle this anyway. Its especially useless in a JVM where the behavior of the scheduler is unpredictable. In a language such as c/c++ where it only runs in one place generally, you can understand the scheduler and help it a bit with yield, but in Java you really do not know for sure where your code will run, and any improvements yield will bring probably can be directed toward inefficiencies in the Thread scheduler of the jvm.
    interrupt is basically a request. It only works on certain methods that are checking for it. So you can't have your thread doing just anything and think you can "interrupt" it. For instance, if you are blocking on a socket operation, interrupt will probably not do anything.

  • Interrupt method (threads)??

    Hello,
    Could someone give me a practical example of the interrupt method that belongs to the Thread class.
    I don't understand why a program would need the interrupt method.
    Thanks in advance,
    Balteo.

    The interrupt method on a thread sets a flag, its up to you in the run method of the thread to check that flag with the interrupted and isInterrupted methods and act accordingly.
    Do not confuse with hardware interrupts, the closest you can get to a hardware interrupt is to wake up a thread of higher priority.
    JO

  • Interrupt a Thread

    I am testing a small application to interrupt the new child thread created.
    My question is:
    How is t.interrupt() able to interrupt the child thread? Is t the main thread that creates a new child thread?
    So,shoudnt t.interrupt() interrupt the main thread rather than the child thread?
    or am I missing something?
    public class UsingFlagToShutdownThread extends Thread{
         private boolean running = true;
         // Entry point for a child thread.
         public void run() {
             while (running) {
               System.out.print(".");
               try {
                 Thread.sleep(1000);
               } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                   break;
             System.out.println("Shutting down thread");
           public static void main(String[] args)  throws InterruptedException {
                UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
                t.start();   // Create a Child Thread.
                Thread.sleep(5000);
                t.interrupt();    // How does t.interrupt() interrupt the child thread created?
    }

    because you are calling the interrupt() method on the "t" instance (the child thread), not the current thread.

  • How to enable EDT to interrupt the worker thread at any time?

    Hello, this is a Swing application - in order for EDT to be responsive, I do the graphical computation in another thread. The computation is very CPU intensive, and I notice the controls are a little jerky - that means the EDT can't get to event handling as fast as I would like. If I do a sleep in the computation thread, instead of work, then controls are smooth as silk - this proves to me that I am doing it right, it's just that the computation is hogging up the CPU. The initial priorities of both EDT and the computation thread are the same (4) - I tried to change the comp thread priority to minimal (1), with success. But even with the higher priority, EDT is still jerky. I even tried (I know gurus are gonna slap me for that) to change the priority of the EDT to max (10), from within the EDT, that was not successfull, the priority stayed at 4, but did not throw SecurityException.
    Anyway, how do I set it up, so that EDT can interrupt my thread, at any time, so EDT never has to wait for CPU?
    Mark

    But then I asked myself - then why, when I leave the computation thread sleeping, and still do "a little bit" of computation in EDT, it is smooth...
    the answer is quite amazing (at least to me, a newbie) - if the comp thread is not doing anything, the result is "simple" and ...
    it turns out, that if the thing that you are drawing, like a series of drawLine() calls, many of them, if the result is simple, like they together form a one long line, then Swing appears to do it faster, than if they do not form anything that can be simplified. It appears, that Swing merges your draw... calls as much as possible to actually make as few drawing calls as possible.

  • How to restart an interrupted thread ?

    Hi All,
    I have to stop a thread and then restart it after sometime. Since, stop() method is deprecated in jdk1.3 so, I m using interrupt() instead of stop() method. Can anyone please tell me , what does interrupting a thread exactly means? Does it termainates a thread completely or not?
    Because , if I use thread.interrupt() and then thread.start() just after it, it raises exception java.lang.IllegalThreadStateException but still starts the thread.
    Prime concern is how to stop and restart a thread without using stop() method??
    Thanx and regards,
    Shweta

    You have to determine in the run method if the thread has been interrupted.
    Usually like this
    run()
    while(!isInterrupted())
    // code body
    you could try this
    boolean restart;
    run()
    while (true)
    if (isInterrupted())
    waitForRestart();
    // code
    waitForRestart()
    restart = false;
    while (!restart)
    sleep(500);
    restart(){restart = true;}

  • How to make a thread NOT get interrupted by the CPU?

    Hello.
    Ok, maybe this might sound trivial, or may expose a fundamental lack in my understand of concurrency... But heres my problem.
    I have 2 threads running, both of the same type.
    After hours of breaking my head, I found out that the reason my program wasnt working is because the CPU was prematurely interrupting one of the threads before it could set a boolean flag to true.
    Basically, my question is this...
    Is there a way I can somehow enclose some of my code such that the CPU should never interrupt the thread while it is running within that enclosed section.

    Hello.
    Ok, maybe this might sound trivial, or may expose a
    fundamental lack in my understand of concurrency...
    But heres my problem.
    I think you nailed it there.
    If you want to notify another thread that is waiting look at the methods.. wait and notify.
    If you need to gaurantee only one thread is running x at one time then use synchronized.

  • Threading Issue, not being interrupted

    Apparently I suck with threading. Take for example, this method.
    public Thread process()
                   return new Thread(){
              public void run()
                   while(!Thread.interrupted())
                       try {
                             Thread.sleep(500);
                             display.asyncExec(new Runnable() {
                                  public void run() { 
                                       pb.notifyListeners(SWT.Modify, new Event()); 
                        } catch (InterruptedException e) {
                             try {
                                  Thread.currentThread().join();
                             } catch (InterruptedException e1) {
                                  // TODO Auto-generated catch block
                                  e1.printStackTrace();
                             e.printStackTrace();
              }When I attempt to do process().start(); the thread will kick off, but when I do process().interrupt(); the thread doesn't stop. No matter what I do i can't seem to stop the thread.

    I just noticed that I am attempting to interrupt a different thread than I started, because everytime I call the method it returns a different thread. Teaches me to copy and paste code...
    Thread t = process();
    t.start();
    t.interrupt();Edited by: sarcasteak on Oct 15, 2009 1:36 PM

  • DatagramSocket.receive() and Thread.interrupt() - Inconsistent behavior

    Hi,
    I currently have an application that does in a seperate Thread receive udp packets in a loop around a Datagramsocket.receive(). Whenever a state change should occur, the thread is being interrupted by Thread.interrupt() in order to exit the DatagramSocket.receive().
    That works nicely on the solaris version of the jvm (1.5.0-11) on x86 and sparc but it does not work on linux intel (i386 and amd64). There the receive simply ignores the interrupt.
    What is the intended behavior ?
    Do I have to move to timeOuts on each receive (which hinders fast state changes as timeouts have to occur and the loop has to be timeouted very often in order to be fast).
    Little tests say: (java 1.5)
    Linux 2.6.18 (32/64 Bit) : no interrupt
    FreeBsd (32/64 Bit): interrupt works
    Solaris 10 (sparc/64x86): interrupt works
    MacOs 10.4: no interrupt
    On Linux 2.6.18, java 1.4 - interrupt works.
    At least a consistent behavior is missing!
    J�rn
    Here is the code:
    SubThread.java:
    package test;
    import java.net.*;
    import java.io.*;
    public class SubThread extends Thread {
         public DatagramSocket ds;
         public boolean quit=false;
         public SubThread() {
              super();
              try {
                   ds = new DatagramSocket();
              } catch (Exception E) {
                   System.out.println("new DS failed: "+E.getMessage());
                   System.exit(-1);
         public void run() {
              byte[] buf = new byte[1000];
              DatagramPacket p = new DatagramPacket(buf, buf.length);
              System.out.println("Started subThread !");
              while (!quit) {
                   try {
                        ds.setSoTimeout(10000); // 10 Seconds
                        ds.receive(p);
                   } catch (SocketTimeoutException E) {
                        System.out.println("ST: Hit timeout !");
                   } catch (InterruptedIOException E) {
                        System.out.println("ST: Interrupted IO Works !: "+E.getMessage());
                        quit=true;
                   } catch (Exception E) {
                        System.out.println("ST: Exception: "+E.getMessage());
              System.out.println("Ended subThread !");
    }Test.java:
    package test;
    public class Test {
         static Integer a = 1;
         public static void main(String[] args) {
              SubThread st = new SubThread();
              st.start();
              try {
                   synchronized (a) {
                        System.out.println("Starting wait (1s) !");
                        a.wait(1000);
                        System.out.println("Sending interrupt()");
                        st.interrupt();
                        a.wait(1000);
                        if (!st.quit) {
                             System.out.println("As interrupts do not work, terminating by timeout !");
                             st.quit=true;
                             System.out.println("Waiting for end!");
                        } else
                             System.out.println("Ending !");
              } catch (Exception E) {
                   System.out.println("Exception: "+E.getMessage());
    }

    What is the intended behavior ?The intended behaviour is defined in http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt()
    ' If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.'
    DatagramSocket not being an InterruptibleChannel, this piece doesn't apply. None of the other pieces apply either, so the fallback applies:
    ' If none of the previous conditions hold then this thread's interrupt status will be set.'
    If you're getting an interrupted read() on one platform, that's a bonus, but it's not the defined behaviour.
    Use a DatagramSocket derived from DatagramChannel.open().socket() and it should work on all platforms.

  • Running thread behaviour on calling interrupt?

    if a thread T1 is running and interrupt is called on this thread,there will be no impact on thread T1 processing/behaviour. To handle this
    we have to call if (Thread.interrupted()) inside run method of thread T1 right?
    Interrupt will have impact when thread is under wait,sleep or join(or methods that throw InterruptedException),Right?
    In above question , impact refers to the case when InterruptedException will be thrown.
    Asked the question at http://www.coderanch.com/t/545582/threads/java/Impact-interrupt-Running-thread but did not get satisfactory reply though i have been thru api doc.

    Interrupting a thread sets a flag for that thread. Setting that flag will cause some blocking operations to throw an exception. e.g. sleep, wait, NIO read. Unless you do one of those operations, setting the flag doesn't do anything which is a problem for those who hope to stop a running thread in an untrusted third party library. ;)

Maybe you are looking for

  • How to add a child at the top of the z-order(above a mobile textinput field)?

    We posted a problem yesterday with PopupManager where in a mobile app, we experience some strange problems, and have had to make our own modal Alert panel to solve the problem. The problem now is that if the alert panel is displayed over a TextInput

  • Email issues with "extended PDFs" for readers...

    I have a Form that will be sent to among 3 employees by email... 2 of the 3 employees only have adobe reader on their desktops...this is why the form was saved in the "extended format" the issue I have is when employee 1 emails the Form to employees

  • How to split iPhoto library and NOT loose metadata?

    My iPhoto library gets too big (30GB); hence I'd like to split it and make two separate libraries, one for 2008, one for 2009. How can I do this WITHOUT loosing all the metadata and file structure: e.g. the albums, the MobileMe gallery, the Faces and

  • Delete a contact

    How do I delete a contact from my contacts list? Just got Windows 8 about an hour ago but I really have no idea.......

  • How to query MP for SMS provider

    Hi , How can i query with remote MP for SMS provider or site server location with vbscript. I am trying to connect to SMS provider from task sequence for updating some data in WMI class instance.