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

Similar Messages

  • Problems overriding interrupt() method in Thread

    I have a class that extends Thread and overrides interrupt() method but it does not seem to be using that. I have some print statements in my method but they never get printed.
    public class ProcessingThread extends Thread {
       public void run () {
           // Processing code
    public void interrupt() {
         System.out.println("Interrupt() method");
         super.interrupt();
    }It won't print the statement in the interrupt() method. I tried to add synchronized as well,. Is it possible or maybe java does not allow this?

    Basically the code that calls it is like in a java tutorial example
    ProcessingThread pt = new ProcessingThread();
    pt.start();
    long timeout = 1000 * 60;   // one minute
    long startTime = System.currentTimeMillis();
    while(pt.isAlive()){
    pt.join(1000);
    if(((System.currentTimeMillis() - startTime) > timeout) && pt.isAlive()) {
        pt.interrupt() ;
    }When it calls pt.interrupt it doesn't call the overrided method (I tried adding a flush but still no indication that it goes into that method)

  • Interrupt method + JDBC connections

    Hi all
    <br>
    Obviously I have a problem with the above :)
    Briefly:
    <br><br>
    - I have a thread that does some things (long operations) and writes results into database
    <br>
    - The main thread has an option to cancel (using interrupt method) the thread on user's request
    <br><br>
    but when I invoke that interrupt method it obviously stops the thread, stops the statement running, takes me to the catch block shown below, but when I try to create a new JDBC connection in that block, I get the exception:
    <br>
    Io exception: The Network Adapter could not establish the connection <br>
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)<br>
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:222)<br>
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:335)<br>
         at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:361)<br>
         at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.java:442)<br>
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:321)<br>
         at java.sql.DriverManager.getConnection(DriverManager.java:525)<br>
         at java.sql.DriverManager.getConnection(DriverManager.java:171)<br>
    <br>
    <b>In other words I am not able to rollback what has been done so far!</b>
    <br>
    I just have to also say that I am using connection pooling and the "long operation" consists of many smaller ones. They all use database. It is a one tree-like process and I can't use just one connection for the whole thing to make it more simple.
    <br>
    <code>
    run()<br>
    {<br>
    try<br>
    {<br>
    //long operation/transaction here<br>
    ...<br>
    }<br>
    catch (Exception e)<br>
    {<br>
    //do some rollback operations corresponding to <br>
    //the above transaction's progress <br>
    }<br>
    }<br>
    </code>
    <br>
    So, can anyone tell me please, what am I doing wrong or is there any workaround for that?
    <br>
    Regards<br>
    Thomas
    <br>
    Message was edited by: <br>
    hrabiatc
    Message was edited by:
    hrabiatc

    Good descriptions at:
    http://www.java.sun.com/products/jdbc/driverdesc.html

  • 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

  • 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.

  • 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

    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).
    */

  • 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.

  • How to view source of native method Thread.start()

    I have already downloaded and unzipped the source code for JDK. I want to view the implementation of Thread.start() method. However, I can only see one line:
    public synchronized native void start();Could anyone tell me how can view the implementation of this method? And generally, how can I view the implementation of a native method?
    Regards,
    Xinjun

    %SRC_BASE%\j2se\src\share\native\java\lang\Thread.c,
    but that only defines a table in which start0()
    forwards you to JVM_StartThread(), wherever that may
    be.You are crossing the boundary between the JDK code and the JVM (Java Virtual Machine). If you have unpacked the Mustang sources [1], take a look at:
    hotspot/src/share/vm/prims/jvm.cpp lines 2421 through 2504.
    This will soon lead you to hotspot/src/share/vm/runtime/thread.cpp
    Hope this helps...
    [1] https://mustang.dev.java.net/

  • Are Static methods Thread safe?

    Hello All
    I have a static method that takes a integer and returns a mathematically processed result.
    Since this method is frequently required, I have placed it in a common class and declared it as static.
    I want to know whether this method is thread safe?

    There's nothing special about static methods, with regard to thread safety. If they access shared objects, then such access will usually need to be controlled by synchronisation; this might be on the object being accessed, some higher-level object or a special object allocated purely as a lock. The only way that you might think of them as special is that there's no instance of the Class on which you can synchronise.
    You can declare a static method as synchronised. If you do, it will be synchronised on the single Class object of the class in which it is declared. This means that only one thread can be executing any part of the method at any one time. However, I understand that the Java Runtime itself sometimes synchronises on this Class object for its own reasons, therefore you might sometimes find a synchronised static method blocks when no other thread is executing it. Usually better, therefore, to explicitly synchronise on some object or other, than to use synchronised static methods.

  • Is this method thread safe?

    Hi Guys
    I have the following code:
    public class MyClass extends HttpServlet {
         HttpSession session;
         public doGet(HttpServletRequest request, HttpServletResponse response)
                                      throws IOException, ServletException                              
              session = request.getSession(false);
              List<AClass> htransactions = (List<AClass>)session.getAttribute("AClass");
                   //do stuff here
    }What I want to know is that if the HttpSession session is declared as a instance variable, does this make it non thread safe? Or is using such a way of for a session fine?
    .

    Steve declared a thumb-rule.
    Bear Bibeault
    sheriff & author
    Member # 24697
    posted Yesterday 9:17 PM
    Yes, variables created inside methods are safe because each thread will get their own copies. Instance variables are unsafe because they are shared across all threads.
    Keep this in memory, hope this was a perfect clarification...you can declare now on the answer.

  • Are the service(), doPost() and doGet() methods THREAD-SAFE?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. If they are not thread safe, How to make them thread-safe?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. They are not.
    If they are not thread safe, How to make them thread-safe?The best way is to avoid writing code that depends on a servlet's thread safety; i.e., no servlet instance variables - keep everything local to the method. Else, you'll want to learn about synchronization.
    [JavaWorld article - Write thread-safe servlets|http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html].
    ~

Maybe you are looking for

  • How can I adjust fonts in one window only without affecting other open windows

    I like to use a chat program and adjust font size without affecting other open windows

  • Gallery Demo doesn't work in IE

    I know i'm re-posting this but i can't belive this is so. So i'm hoping people just didn't see my second message rather than simply ignoring the fact that the gallery demo by Adobe doesn't work right in IE (at least in mine with SP2). If you notice w

  • Take long time for loading

    Hi Experts, One of my data target (Data comming from another ODS) is taking long time for loading, basically it takes below 10 times only, but today it is running from last 40 minesu2026 In Status Tab it showing.... Job termination in source system D

  • Regarding back ground job

    hi, I have a  program which includes a bdc  code.when i run that program it will take me to mb1a i.e goods issue.i have to press enter each time for each and every item .Is there any way i can do this as background job. i haven't done anything relate

  • Truncate on a partitioned table

    hi all. A table has some paritions.I try to delete all rows from one of these partitions. How to use truncate to do this? Regards Bacer