Killing a Thread

In recent versions of the JDK they deprecated the stop() and destroy() methods. They did so because those methods can kill a thread in a "dirty" way. The replacement approach is to have a while(isRunning){} loop in the run() method and to set isRunning to false via a call to another method.
I have a scenario that can be described as follows (taking some liberties with syntax):
public void run(){
while(isRunning){
JobInterface job = ... code to instantiate the job via reflection.
job.execute();
isRunning = false;
Here, although the interface is standard, the job is one of many possible applications written by other people and without access to their source code. The JobInterface is already defined and there are many applications already in production that use it - in other ways we can't expect to change the code of the reflected jobs. Further, setting isRunning to false while the job is executing its execute() method (possibly for hours) isn't going to help.
So the question here is, how to kill a thread like this one... while it is still waiting for job.execute() to end?

bmelloni wrote:
I only need the forced thread stop for those jobs that cannot be modified to comply with the above. At that point whatever consequences there are for those jobs will have to be accepted. If resources (i.e.: database) are left in messed up states... tough. It will have to be handled then (and maybe it will give incentive to make those black-box jobs compliant).I doubt it. Unless someone quite high-up is informed, these things are often shelved until something breaks. My suggestion would be to put your (our?) concerns in writing, and make sure you get a reply in kind from your management before you do anything. Once the finger-pointing starts, it's usually the sharp end that suffers.
But we aren't even planning to use this capability to stop threads unless our server is about to crash - in which case the consequences would have been the same.Better make sure it's VERY difficult to do accidentally then.
In other words, don't worry... we are not stupid.I don't think anyone said stupid...Naive, maybe.
Winston

Similar Messages

  • How can I kill a thread.

    I have read the many threads about killing a thread but they dont answer the question I need to know.
    In class#1 I have the following snipet of code:
    for (int i=0; i < docs.size(); i++)
        try {
            boolean blncompleted = false;
         Map object = null;
            OntologyCreatorThread  ontThread = new OntologyCreatorThread ();
         ontThread.start();
         ontThread.join(15000); // Allow thread to process for up to 15 seconds.
         // If thread is still running, kill the thread.  I dont care about
         // clean up since its only using memory and cpu, no DB is ever touched.
         if (ontThread.getState().toString().equals("RUNNABLE")){
             ontThread.interrupt();
                ontThread.stop();
                // set flag to false
             blncompleted = false;
            else {
                // set flag to false and do a ton of other processing.
             blncompleted = false;
             object = ontThread.getObject();
        catch (Exception Ex){
            Ex.printStackTrace();
    In my thread I have the following:
    public class OntologyCreatorThread extends Thread {
        Map object = null;
        public OntologyCreatorThread(){
        public void run() {
           try {
             // The line below takes forever to run sometimes.
             object = functionCallToApi(stringOfText);
        public Map getObject() {
         return objects;
    If the thread takes to long to run I just want to kill it.
    I have tried interupt and stop and both dont work.  Inside the run method of the thread I call an external API
    which I pass a string of text.  I can not get into that code because its from a Off the shelf product that we dont
    have the code to.  If the call in the run method takes to long I want to just kill this thread in the main class(#1). 
    No matter what I do I cant get the damn thing to stop.
    The line below takes forever to run.
             object = functionCallToApi(stringOfText);
    Putting it in a while loop wont solve this problem because the processing is still taking place in the call to the api.
    Thanks in advanceMessage was edited by:
    Storm897

    Couple of things to consider:
    1. Note that Thread.interrupted() and t.isInterrupted() are very different methods. The former clears the interrupted status so that a subsequent call will return false. The latter does not affect the interrupt status on the thread.
    2. If your "atomic step one" catches an Exception, then you might be swallowing an InterruptedException. Basically the rule when a Thread is interrupted is that if it is in a blocking call, an InterruptedException is thrown. Otherwise, isInterrupted is set to true. So if you have blocking (I/O) calls in "atomic step one" and you're catching Exception, then it might be that the InterruptedException goes completely unnoticed.
    3. If "atomic step one" takes a long time and you really want to abort the thread instantly, then you need some kind of method for doing so--you need to program in safe "stopping points". For example:
    public class Helper implements Runnable {
       private boolean _continue = true;
       public void cancel() {
          _continue = false;
       public void run() {
          _continue = true;
          try {
             // Do something until in safe/stable state
             if(!_continue) return;
             // Do something until in safe/stable state
             if(!_continue) return;
             while(_continue) {
                 // process single record in large data set
                 // Safe to stop at the end of each loop
             if(!_continue) return;
             // Do something else . . . etc.
          } catch(InterruptedException ie) {
             _continue = false; // Unnecessary, but here for illustration
    }Casual programmers often don't care whether the thread stops safely or not, but it really is important especially if you are in the middle of some kind of transaction. That's why destroy(), cancel() et al are deprecated.

  • Killing a thread easily?

    Hello, I'm working with a thread class that looks like this:public void run() {
         while (true) {
              Socket client = aServerSocket.accept();
              // do stuff
    }The problem is kind of obvious, as it is, it never stops unless you kill the VM, eventually leading to dozens of threads. Even if I changed the loop variable, the thread would still hang around while accept() blocked for input. I want to kill it when I know it's useless. My first attempt was:     while (!Thread.interrupted()) {and then calling interrupt() on the thread - oops! - serversockets aren't interruptable, so the thread still never stopped. I was going to come here and post then, but I went back and read the api for server sockets again, and found that calling close() on the socket will interrupt the blocking accept(). So:     while (!aServerSocket.isClosed()) {Unfortunately, I'm not sure if that actually works, or not, because my app which used to take up < 1% of CPU time when running was now taking more than 50%, so I shut it down - at least when there are lots of threads, they are all sleeping and don't eat the cpu :(
    Does anyone have any suggestions on how to stop threads ?

A: Killing a thread easily?

ejp: I'm not sure what you're referring to, but from the ServerSocket api:
"close() : Closes this socket. Any thread currently blocked in accept() will throw a SocketException."
There are other things in the 'do stuff' part of the loop that can throw exceptions, but I don't want to break out of the loop. I omitted the try around 'accept' and 'do stuff' for simplicity in my original diagram. I tried rearranging my try statements like so:
try {
     while(true) {
          Socket client = aServerSocket.accept();
          try {
               // do stuff
          } catch ()
} catch ()So that if the accept call threw an exception, it would drop out of the while loop. Unfortunately, when I tried running this the program took up >25 % of my CPU time to run, instead of < 1 % as usual, like my third try above.
hiwa: Sorry I didn't explain more clearly. Several of these threads are being spawned to listen to multiple sockets. Sometimes the connection gets dropped, due to lag or internal reasons, and it reconnects on a new socket with a new thread, but the old socket and thread are still hanging around because it's stuck in the while(true) loop and accept blocks indefinately.

ejp: I'm not sure what you're referring to, but from the ServerSocket api:
"close() : Closes this socket. Any thread currently blocked in accept() will throw a SocketException."
There are other things in the 'do stuff' part of the loop that can throw exceptions, but I don't want to break out of the loop. I omitted the try around 'accept' and 'do stuff' for simplicity in my original diagram. I tried rearranging my try statements like so:
try {
     while(true) {
          Socket client = aServerSocket.accept();
          try {
               // do stuff
          } catch ()
} catch ()So that if the accept call threw an exception, it would drop out of the while loop. Unfortunately, when I tried running this the program took up >25 % of my CPU time to run, instead of < 1 % as usual, like my third try above.
hiwa: Sorry I didn't explain more clearly. Several of these threads are being spawned to listen to multiple sockets. Sometimes the connection gets dropped, due to lag or internal reasons, and it reconnects on a new socket with a new thread, but the old socket and thread are still hanging around because it's stuck in the while(true) loop and accept blocks indefinately.

  • Kill Execute Thread

    Is there a way to kill specific Execute Threads. We are in a situation when an
    MDB would not acknowledge specific messages and those MDBs(which run on default
    execute queue) will not terminate. We would like to kill those threads when we
    want to undeploy the app. IF there are MDBs running on other threads, then the
    app would not end gracefully. See post
    http://newsgroups.bea.com/cgi-bin/dnewsweb?utag=&group=weblogic.developer.interest.jms&xrelated=10750&cmd_thread_next.x=45&cmd_thread_next.y=11
    So the question: Is there a way to kill specific execute threads thru JMX or some
    other way?
    Thanks
    Raj

    What do you mean by "executes a script"? Is this execing a shell or is it just running some Java code?
    You can't kill a Thread if it doesn't want to be killed. The deprecated Thread.stop method will atempt to cause an asynchronous ThreadDeath exception in the thread but this is very dangerous as it can leave shared objects - including system library objects - in an unstable and unusable state.
    The preferred mechanism is cooperative termination whereby you use the Thread.interrupt method to indicate to the target thread that it should cease what it is doing, when it is safe to do so. The target thread must be responsive to interrupt requests either by directly checking Thread.interrupted, or by using methods that are themselves responsive to interrupts (typically blocking methods that will throw InterruptedException if interrupted). Some blocking methods (mainly IO operations) won't respond to interrupt, nor does the acquisition of a monitor lock, so there are never any guarantees. If the thread can stuck in an "endless loop" then something in that loop needs to check for interrupts.

  • Best way to stop or kill a thread

    hi what would say is the best way to kill a thread in this situation.
    1. I have 200 threads
    2. Each Thread has a reference stored in a hashtable example;
    for( int i=0; i<200; i++){
    Thread t = new exThread(i);
    hashtable.put(Integer(i) , t );
    t.start();
    each thread is running in an infinite while loop.
    now what would you say is the best way to kill the thread from this parent class.
    One thought of mine is to access get the reference and call stop.
    example;
    Thread tRef = hashtable.get(Integer(100));
    tRef.stop();
    In the stop method i would clear up whatever it was doing - release resources properly and - when it goes out of the stop scope , i'm guessing it would be destroyed.
    Any thoughts or other recommendations ?
    Stev

    Limeybrit is correct....the way Sun recommends (and which I use) is a boolean at the top of your runnable code. If false, you simply return and don't hit any of the other code in the runnable method.
    At the end of your run process, you simply set your Thread to null and wait for the garbage collector to clean up.

  • How to kill a Thread?

    Hello,
    My question is simple how to kill a thread.
    The background is a call to a method in a third party API, crawler4j, that locks the entire program.
    The design of crawler4j is "You should stop it when you think it's enough (ctrl+c)" but as I use it only as a step in a larger program I want to stop it programmatically and not by "ctrl+c" as they have designed the API.
    This is the locking callcontroller.start(MyCrawler.class, numberOfCrawlers);So I made a thread public class MyCrawlController extends Thread {
    public void run(){
      controller.start(MyCrawler.class, numberOfCrawlers);
    }And in my main method
    MyCrawlController mCC = new MyCrawlController();
    mCC.start();
    Thread.sleep(180000);
    //Here I want to kill the mCC and all it's threadsOne problem is that my program never terminates. Probably due too the JVM not realizing that I don't want it to count mCC and it's spawned threads as alive. Any idea on how to solve this. For now I can only exit the program with System.exit(0); and I don't want that. So I need a way to stop the mCC's threads and get the JVM not to count them. Any idea on how to solve this. Even better if they can be taken by the GC.

    Farmor wrote:
    Thanks for the answer.
    I came to think about daemons and solved the problem with mCC.setDaemon(true);Really stupid that one has to do several programs and tie them together only to kill a thread.
    As I only do this for other learning purposes and won't use this code or program after this week I will modify crawler4j, open source, and make myself a custom good method that will terminate itself and return to the main method properly.There are some fairly difficult problems with a number of aspects of concurrency if you forcibly stop threads, which is why Thread.stop() and related methods have long been deprecated.
    It's a pity that Java can't respond to kill signals (like Ctrl-C) in a tidy way. I think they're all tied up with some of the JVMs internal processes.
    In general people wind up using sockets instead of signals.

  • Kill a thread and remove the element from the vector

    Hi All
    I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
    Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
    However, I want to delete this element from the Vector now.
    Can someone please throw some light on this?
    Here the code I have written for this:
    try
         System.out.println(counter);
         int xCoord = generator.irand(25,200);     // X-coord of AP
         int yCoord = generator.irand(25,200);     // Y coord of AP
         listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
         listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
         for(int i=0;i<vnuBS.returnBSList().size();i++)
              if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
                   double c = exponential() * 10000;
                   long timeToService = (long)c;
                   System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
                   vnuBS.returnBSList().get(i).reduceChannelCounter();
                   System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
                   mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
                   mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
                   mobileNodesThread.elementAt(mobileNodeCounter).start();
                   mobileNodesThread.elementAt(mobileNodeCounter).join(100);
    //                              System.out.println("Died");// thread dies after join(t) milliseconds.
                   System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
              else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
                   listMN.remove(this.listMN.lastElement());                         //dropcall
                   System.out.println("Removed "+mnId);
                   removeCounter++;
                   mnId = mnId--;
                   mobileNodeCounter--;
              mnId = mnId+1;
         Thanks a lot.

    I'm not sure if what you are trying to accomplish is correctly implemented.
    The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
    Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
    I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish?

  • Killing Parent thread can kill child thread

    hi frnds
    can u help me on thread
    i want to know if i am kill my parent thread.can it automatically kill chhild thread also.
    and i want to know is there any way in java to kill thread
    plz reply

    ajju29 wrote:
    and i want to know is there any way in java to kill threadNo, not safely and not reliably. Since there's no way to "kill" a thread without its cooperation, the previous question is not relevant as well.
    What you want to do is set some flag that your thread periodically checks and maybe send an signal and/or interrupt to tell the thread to check the flag earlier. The thread should then quit on its own.
    Everything else is unfixably broken.

  • How can I kill all Threads of the same class from within the run() method?

    Ok
    I have a class called Consumer that extends Thread
    I have several Consumer threans running... but, when a certain condition is true (within the run() method) in ANY of the threads, I want to kill ALL the threads of that object.
    is this possible?

    I know this is gonna be too demanding, but can someone please tell me why my Consumer's run() method never reaches the System.out.println( "ALL CONSUMING DONE") line
    Create a multi-threaded prime number calculator that is based on the producer-consumer model
    using semaphores. Your program should be able to check for prime numbers in a range specified
    by the user and with a variable number of threads. Example:
    $ java PrimeFind 3 5000 10000
    should use 1 producer and 2 consumers (3 threads in total, obviously the minimum is 2) to find all
    the prime numbers in the range [5000,10000].
    The producer should: use a buffer to store candidate numbers that have to be checked for
    primality.
    Consumers should: read from the buffer, check if a number is prime and update the status of the
    program accordingly (e.g. show the number on the screen, or save it to a file)
    import java.util.concurrent.Semaphore;
    import java.io.*;
    public class Assign1 {
    static int fromThisNumber;
    static int toThisNumber;
    static int numberOfThreads;
    static int buffer[];
    static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                         an "OK" to the consumers*/
    static Semaphore critical;  /*This is a Mutex semaphore. It allows only 1 consumer
                                         to enter his critical section.
    static Semaphore counter;     /*This semaphore acts as a counter.
                                        Instead of having a global variable
                                         incremented each time, we just release()
                                         this semephore when we find a prime number
                                         Because remember that release() increments permits
    static Producer prod;
    static Consumer cons[];
    static int in=0;
    static int out=0;
    static PrintWriter outFile;
         public static void main (String args[]){
              try{
                   outFile=new PrintWriter(new FileWriter("primes.txt"));
                   }catch(Exception e){}
              numberOfThreads=Integer.parseInt(args[0]);
              fromThisNumber=Integer.parseInt(args[1]);
              toThisNumber=Integer.parseInt(args[2]);
              buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
              ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                      for the Producer to produce atleast a
                                                      item. Suppose ready was 1 and if
                                                      Consumer ran first he would be in an
                                                      empty buffer */
              critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                         the first Consumer thread tries
                                                         to enter its critical section, it
                                                         should be allowed to;
                                                         Subsequent threads will have to
                                                         wait since only 1 thread can
                                                         access its critical section at a time*/
              counter=new Semaphore(0,false); // duh!
              cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                                is taken by the Producer*/
              //Creating Producer object
              prod=new Producer();
              //Creating the Consumer object and start the thread.
              for(int i=0;i<cons.length;i++)
                        cons=new Consumer();
                        cons[i].start();
              prod.start();          
              //Printing to screen and file
    /*          for(int i=0;i<buffer.length;i++)
                   if(buffer[i]!=0)
                             System.out.println(buffer[i]);
                             outFile.println(buffer[i]);
              System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
              outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
              outFile.close();*/                    
    static class Producer extends Thread {
         public void run(){try{
              while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
                   {     System.out.println("producing");     
                        buffer[in]=fromThisNumber;
                        in++;
                        fromThisNumber++;
                        ready.release();
              catch (Exception e){e.printStackTrace();}
              System.out.println("ALL PRODUCING DONE");
    static class Consumer extends Thread {
         int tempout=0;
         public void run(){try{
              System.out.println("before while"+this.getId());
              while(tempout<=in)
                   System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
                   ready.acquire();
                   System.out.println("before critical.acquire"+this.getId());
                   critical.acquire();
                   tempout=out;
                   out++;
                   critical.release();               
                   if(!isPrime(buffer[tempout]))
                        {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
                   else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
                   critical.acquire();
                   tempout=out;
                   System.out.println("tempout:"+tempout+" of "+this.getId());
                   critical.release();
              System.out.println("ALL CONSUMING DONE"+this.getId());
         catch(Exception e){e.printStackTrace();}
         //Prime number-checking method     
         public boolean isPrime(int n){
              for(int i=2;i<=(n/2);i++)
                   if(n%i==0)
                        return false;
              return true;
    ======================
    import java.util.concurrent.Semaphore;
    import java.io.*;
    /* 3 questions to ask Barlas
    * Why error if I start the Consumer threads before Producer
    * Why does the counter semaphore always give a +1 result at the end
    * Is there a way I can verify that all the work is not being done by only 1 consumer thread? In other words, the workload is being shared properly
    * if I put ready.acquire() outside or inside the while loop, its not making any difference, why?
    * Strangely, its not making any difference if I playing with the release() and aquire() of the semaphores, WHY?!?!
    public class Assign1 {
    static int fromThisNumber;
    static int toThisNumber;
    static int numberOfThreads;
    static int buffer[];
    static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                       an "OK" to the consumers*/
    static Semaphore critical; /*This is a Mutex semaphore. It allows only 1 consumer
                                       to enter his critical section.
    static Semaphore counter;     /*This semaphore acts as a counter.
                                  Instead of having a global variable
                                       incremented each time, we just release()
                                       this semephore when we find a prime number
                                       Because remember that release() increments permits
    static Producer prod;
    static Consumer cons[];
    static int in=0;
    static int out=0;
    static PrintWriter outFile;
         public static void main (String args[]){
              try{
                   outFile=new PrintWriter(new FileWriter("primes.txt"));
                   }catch(Exception e){}
              numberOfThreads=Integer.parseInt(args[0]);
              fromThisNumber=Integer.parseInt(args[1]);
              toThisNumber=Integer.parseInt(args[2]);
              buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
              ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                      for the Producer to produce atleast a
                                                      item. Suppose ready was 1 and if
                                                      Consumer ran first he would be in an
                                                      empty buffer */
              critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                      the first Consumer thread tries
                                                      to enter its critical section, it
                                                      should be allowed to;
                                                      Subsequent threads will have to
                                                      wait since only 1 thread can
                                                      access its critical section at a time*/
              counter=new Semaphore(0,false); // duh!
              cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                                is taken by the Producer*/
              //Creating Producer object
              prod=new Producer();
              //Creating the Consumer object and start the thread.
              for(int i=0;i<cons.length;i++)
                        cons[i]=new Consumer();
                        cons[i].start();
              prod.start();          
              //Printing to screen and file
    /*          for(int i=0;i<buffer.length;i++)
                   if(buffer[i]!=0)
                             System.out.println(buffer[i]);
                             outFile.println(buffer[i]);
              System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
              outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
              outFile.close();*/                    
    static class Producer extends Thread {
         public void run(){try{
              while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
                   {     System.out.println("producing");     
                        buffer[in]=fromThisNumber;
                        in++;
                        fromThisNumber++;
                        ready.release();
              catch (Exception e){e.printStackTrace();}
              System.out.println("ALL PRODUCING DONE");
    static class Consumer extends Thread {
         int tempout=0;
         public void run(){try{
              System.out.println("before while"+this.getId());
              while(tempout<=in)
                   System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
                   ready.acquire();
                   System.out.println("before critical.acquire"+this.getId());
                   critical.acquire();
                   tempout=out;
                   out++;
                   critical.release();               
                   if(!isPrime(buffer[tempout]))
                        {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
                   else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
                   critical.acquire();
                   tempout=out;
                   System.out.println("tempout:"+tempout+" of "+this.getId());
                   critical.release();
              System.out.println("ALL CONSUMING DONE"+this.getId());
         catch(Exception e){e.printStackTrace();}
         //Prime number-checking method     
         public boolean isPrime(int n){
              for(int i=2;i<=(n/2);i++)
                   if(n%i==0)
                        return false;
              return true;
    ===========================
    BTW, when I tried to change extends Thread to implements Runnable I got some kinda of error.
    Actually, my program is pretty complete... its just that something if messed up in my Consumer's run() method's while loop... I think
    I know guys its crazy to ask ya'll to look at so much code, but.... I'd really appreciate it. This assignment is killing me, been at it since 10 hours now....

  • Kill Event thread or abort/restart main VI

    I am looking for a method of killing off an event thread once it is in the middle of executing.  A description of my problem is below (I am using labview 8.2).
    My main VI is reading my DAQ and constantly updating the main control panel with the data and logging the data at operator defined rates.
    The user can then select different functions for the system to execute using an enumeration and a Boolean control.
    When the user selects the Boolean control (run button) an event is triggered, the ENUM is read, and various sub-vi's execute to complete the function (none of the sub-vis have visible control panels all of them use some of the data from the main vi's controls/indicators passed by reference).
    The user also has a stop button.  If pressed another event is generated.  I would like to kill the run event in this case, at any point in its execution (long delays in some of the sub-vi's).  Then I can set the system back to default and continue on selecting another function in the enumeration and run button press.
    I would also considering aborting the main vi and then restarting it as long as the front panel remains open.

    I appreciate the reply.  I agree that the event cannot be killed, I have tried several "tricks".  The code does go into the stop event while the run event/sub vi is executing. 
     I had the ref to the stop button wired into the sub-vi's already.  Some of these vi's are fairly in depth, do you have a recommendation to continuously read its state without getting into every loop etc that is in the sub-vi?  I was trying not to monitor this buttons state at every point in the sub-vi's block diagrams.
    Thanks

  • How do you kill a thread?

     

    First, you have to design the thread to allow itself to be killed. This is usually done by checking periodically as a thread goes through its task loop.
    This question comes up a lot here, but here's a link to a recent discussion that includes examples.
    http://forum.java.sun.com/thread.jsp?forum=31&thread=495784

  • Detecting (And Killing) Abandoned Threads

    Hi All,
    I'm going to try to make my question as simple as possible: I'm trying to use the service guardian to automatically detect an abandoned thread and kill the originating process. So basically I set up a test that ends up with an abandoned thread and configured service Guardian... but it didn't work :D
    What I first did is setting the guardian's timeout to be very short (6 seconds). When I do that, what I get is:
    2010-03-26 10:03:29.389/0.859 Oracle Coherence GE 3.5.3/465 <Info> (thread=main, member=n/a): Loaded cache configuration from "file:/C:/workspaces/POC/InvocableTest/bin/coherence-cache-config.xml"
    2010-03-26 10:03:29.952/1.422 Oracle Coherence GE 3.5.3/465 <D5> (thread=Cluster, member=n/a): Service Cluster joined the cluster with senior service member n/a
    2010-03-26 10:03:35.295/6.765 Oracle Coherence GE 3.5.3/465 <Error> (thread=Cluster, member=n/a): Attempting recovery (due to soft timeout) of Guard{Daemon=TcpRingListener}
    2010-03-26 10:03:35.904/7.374 Oracle Coherence GE 3.5.3/465 <Error> (thread=Cluster, member=n/a): Terminating guarded execution (due to hard timeout) of Guard{Daemon=TcpRingListener}
    Coherence <Error>: Halting JVM due to unrecoverable service failure
    2010-03-26 10:03:36.904/8.374 Oracle Coherence GE 3.5.3/465 <Error> (thread=Termination Thread, member=n/a): Full Thread Dump
    ThreadCluster
         java.lang.Object.wait(Native Method)
         com.tangosol.coherence.component.util.Daemon.onWait(Daemon.CDB:18)
         com.tangosol.coherence.component.util.daemon.queueProcessor.service.Grid.onWait(Grid.CDB:6)
         com.tangosol.coherence.component.util.Daemon.run(Daemon.CDB:39)
         java.lang.Thread.run(Unknown Source)
    So that's before the thread gets abandoned... it seems that it detects a deadlock when starting coherence. But that's ok, I know the service guardian is working. The problem comes when I set the timeout to something more realistic: 35 seconds for instance. I run my test, the thread gets to an abandoned state and the service guardian does not see it :(
    Any Ideas?
    h4. My override config is:
    <coherence>
    <cluster-config>
         <service-guardian>
              <timeout-milliseconds system-property="tangosol.coherence.guard.timeout">6000</timeout-milliseconds>
              <service-failure-policy>exit-process</service-failure-policy>
         </service-guardian>
    </cluster-config>
    <logging-config>
    <severity-level system-property="tangosol.coherence.log.level">5</severity-level>
    <character-limit system-property="tangosol.coherence.log.limit">0</character-limit>
    </logging-config>
    </coherence>
    Thanks!
    Fernando
    Edited by: ZeoS on Mar 26, 2010 7:13 AM

    it's an Invovable running on the server.
    The description in the debugger is: InvocationServiceWorker
    Maybe this helps:
    10-03-26 12:03:41.279/72.663 Oracle Coherence GE 3.5.3/465 <Error> (thread=Abandon, member=1): A worker thread "InvocationServiceWorker:0 executing task "Message "InvocationRequest"
    FromMember=Member(Id=1, Timestamp=2010-03-26 12:02:29.866, Address=10.31.106.86:8088, MachineId=32598, Location=site:someSite.com,machine:ZeoSWorkStation,process:1084, Role=TestInvocableExpiration)
    FromMessageId=0
    Internal=false
    MessagePartCount=0
    PendingCount=0
    MessageType=1
    ToPollId=0
    Poll=null
    Packets
    Service=InvocationService{Name=InvocationService, State=(SERVICE_STARTED), Id=3, Version=3.1, OldestMemberId=1}
    ToMemberSet=MemberSet(Size=1, BitSetCount=2, ids=[1])
    NotifySent=false
    InvocationRequest{Query, Task=TestInvocableExpiration.SocketInvocable@16b352c}
    }", did not respond to 8 interrupt requests. The execution was canceled. The thread is abandoned...
    Fernando

  • Killing a Thread that runs a C code

    Hi,
    In my Java application, i use a library written in C++ using JNI. The tasks that are executed by the C library sometimes take a lot of time, so I was considering adding an option for the user to be able to stop it. As these tasks are running in a thread, i was wondering whether there is a way to safely do this?
    I have searched the forum, but did not manage to find some post with similar problem. As far as I could see, stopping a thread in general is not safe...
    Suggestions guys?
    Thanks

    shashi_rajak wrote:
    you can stop the thread by setting the value of thread to null.---------------> the thread will not be stopped immediately.So setting it to null won't change anything at all. Yes, that's correct, but that isn't what you said previously.
    better put a guarded block in the thread code .What's a guarded block?
    so that thread will not process the rest of code.Ah, you mean that you need some kind of flag, latch or other way to signal. That's correct, but you never said that (you actually still haven't said that)
    >
    >
    user can again start the thread by starting the thread.-----------------> its mean by creating a new thread object. We aren't mind readers. Calling start of a new thread will of course work, but that isn't what you said.
    since you cannot start a already started thread its throws invalid State Exception.Yes, we knew that. That's why we corrected you.
    this current forum is not for beginner . Eh. Hmm.. Ok, so I registered in 2000, and have quite many posts, and you came to the conclusion that I'm a beginner?
    It has the heading Java Programming " not "New to java". please use your brain.Did you use yours?

  • Killing a thread ( runnable ) - problem

    Hi,
    I already posted about this, and got a good answer.
    But, I still have a probalem :
    Here is a piece of my code :
    // this is the bean which is in the EPN and I want it to create a thread that prints something :
    public class EventListener implements StreamSink,com.bea.wlevs.ede.api.DisposableBean ,InitializingBean {
    // the relevant methods:
    RunnableTestBean runnableTestBean; // this is the thread which suppose to print ..
    public void destroy() throws Exception {
              System.out.println("destroydestroydestroydestroydestroydestroydestroy");
              runnableTestBean.suspend();
         public void afterPropertiesSet() throws Exception {
              runnableTestBean=new RunnableTestBean();
              runnableTestBean.run();
              //System.out.println("afterPropertiesSetafterPropertiesSetafterPropertiesSet");
    and the class RunnableTestBean :
    public class RunnableTestBean implements RunnableBean {
         boolean stopped=false;
         public void run() {
              while ( !stopped){
                   System.out.println(" printing...");
                   try {
                   wait(5000);
                        //Thread.sleep(1000);
                   } catch (InterruptedException e) {
                        System.out.println(" Stoping thread ??");
                        e.printStackTrace();
         public void suspend() throws Exception {
              stopped=true;
    The thing is that when I use the method as above :
    public void run() {
              while ( !stopped){
                   System.out.println(" printing...");
                   try {
                   wait(5000);
                        //Thread.sleep(1000);
                   } catch (InterruptedException e) {
                        System.out.println(" Stoping thread ??");
                        e.printStackTrace();
    When I undeploy the application , the destoy method ( in EventListener class ) is not called !
    but,
    if I implement the run "run" method like this :
    public void run() {
    System.out.println(" Something ");
    than everything is fine!
    The differrence as you can see , is that when I use an infinite loop - the destroy method never called ( seems that the caller waits for it to stop , and that's why the
    destroy method not called )
    When i don't use the infinaie loop- it's OK.
    So, any help ?
    Thanks ..

    Looking at the code that you have posted, the problem is that you are calling runnablebean.run() method in afterPropertiesSet (instead of starting a thread in which the run method is called). So, it looks like it will get stuck in afterPropertiesSet for ever.
    The recommended approach for what you are trying to do is to make the EventListener class implement RunnableBean (instead of having a separate class that implements RunnableBean that gets called from afterPropertiesSet). This means that at application startup time, this EventListener's run() method will be called by OCEP framework code in a separate thread. You can still use the suspend() method to stop the thread similar to how you are doing in your code now.

  • Monitoring inactivity - killing off thread if client isn't taking anymore

    Hi all,
    I have a small little app - client server type. The client is an applet sitting on a webserver. I'm just starting to do some testing here and I've run in to a fairly obvious problem.
    When I load the page the client connect to the server spawning a new thread on the server. If you would actually use the tool and click that OK button the server will carry out the work - forward the result to the client and then closes the connection and gracefully gets rid of the thread.
    However - If you don't click the button - say just cnahging the html of the webpage and keep reloading the page, more and more threads are spawned and they don't seem to time out or die. I need to add functionality that monitors the connection and decide that lets say, if the client has not made a request in 30 min - close the connection and end the thread.
    I realize this must be a very common scenario but I have not found any good texts discussing this issue.
    Can someone please point me into the right direction.
    Thanks,
    Dan

    That is so annoyingly simple I have to laugh - can't believe I did not think about that!
    That's much less of I code change than I was preparing myself for. Will go ahead and do that now.
    thanks!

  • Maybe you are looking for

    • Crystal Reports - Unhandled exception

      Good day all When running a report in Crystal reports addon I get the following error: "Unhannled Exception hes occured in you aplication. If you click continue.............." I am running crystal reports 2.0.0.7 on a 64bit server. Can this error be

    • How to unlock a row if i use FOR UPDATE clause

      In procedure if we use FOR UPDATE clause, it will lock particular row and allow only one client to update whereas other client can only fetch data in the same row at that time. My question is when will it unlock the row, what should we do to unlock t

    • Import packageless classes in a jsp : tomcat 5.0.16

      Hi all, I am trying to import a class, say one.class, which is stored in the /WEB-INF/classes folder of the webapplication into a jsp page. Like, <%@page import="one"%> I get the following error, C:\jakarta-tomcat-5.0.16\work\Catalina\localhost\test\

    • Help creating 2D array from tab delimited text file

      I can print the info from the file, but darned if I can't make a 2-D array. import java.util.regex.*; import java.io.*; public final class goodSplitter {     private static BufferedReader br;     private static BufferedReader br2;     private static

    • HT4623 why do i have to enter my apple id and password everytime to open an app?

      I updated my ipad to the latest OS and now everytime i want to open an app i have to enter my apple id and password   how can i change this