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.

Similar Messages

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

  • How can i kill the Adobe Reader session right away?

    Hello
    I have developed an interactive form, my_form. And we launch / render this my_form in (ERP / SAP) application's portal IE browser, well.
    Say, user opened this form, worked on it, submitted (we have our own submit button) and closed the window by clicking the top right corner's X button, but user is seeing stll the red Reader icon on the bottom bar, even thought the user is closed the window completely
    If user try to close this reader red reader icon explicitly, user is getting the other exception popup as Runtime error as described here http://forums.adobe.com/thread/391738
    Hence, am thinking to KILL the reader session right away the moment user closes the window, pls. let me know,
    1) How can i KILL the reader session via JavaScript, is it possible?
    2) if so, what the JS code i need to put and
    3) in which event pls.?
    Thank you

    In to my original posting, am attaching these pics
    On my desktop it looks like below,
    1) Even though user is closing the window but still the reader icon is lying on the bottom
    2) Once user double cliks the above red icon, user is getting below popup
    Thank you

  • I click a link but it doesn't open. Instead I get a popup saying "Open the link in a new window," "Open link in a new tab," etc. How can I kill this popup or whatever it is forever?

    I click a link but it doesn’t open. Instead I get a popup saying “Open the link in a new window,” “Open link in a new tab,” etc. How can I kill this popup or whatever it is forever?

    That happens if the server sends the file as text/plain.
    You can see this if you open "Tools > Page Info > General": Content-Type: text/plain
    Files send this way will always open in a tab.
    *https://developer.mozilla.org/Tools/Web_Console

  • How can I close core thread in ThreadPoolExecutor?

    If I use unbounded LinkedBlockingQueue in ThreadPoolExecutor and set the core pool size to 5. When more than 5 tasks are submitted, there will be 5 threads created to handle the request. After finish, these threads will not be closed. How can I make the threads in core pool be closed when finishing their job? I couldn't use maximum pool for that I do need an unbounded queue.

    If you really want that functionality, set the core pool size to 0, the maximum pool size to 5 or greater, and the keepAliveTime to 0L. This will remove excess threads as soon as their tasks have completed.
    It's very wasteful though if you plan on executing the tasks repeatedly to create new threads everytime you submit a task. One of the benefits of using a thread executor is not having to construct and start a Thread object everytime you run a task.
    Brushfire,

  • How can i kill a job in BW

    Hi,
    Any budy please help me that how can i kill a background job in BW
    Cheers,
    KGB

    hi u can kill job in SM 37 also.
    also u can cancel in SM50.also use tis link
    How to stop scheduled job in bw.
    Hope it solves your query
    Thanks,
    pathak
    Edited by: npathak on Aug 2, 2010 9:09 PM

  • How can I make watch thread disable to a single user

    How can I make  "watch thread" disable to a single user in the fourm administrator.

    If you have iWork Pages can be used to do what you want.
    OT

  • How can I kill database connections

    I would like to know how can I kill all the database connexion at the end of an application. I'm using acces
    thx

    use con.close() in a finally statement after your catch blocks that tests whether con equals null. If con != null, then con.close();
    example:
    finally {
              //close the database connection.
              try {
                      if (con != null) con.close();
              catch (SQLException e) {
    }

  • I lost my iPhone. how can I kill it?

    I lost my iPhone 4s at airport in oversea.
    Unfortunately, I could not find that.
    When I get back to US, I just bought one and recovered my contact and app etc on my new iPhone.
    But, I don't want somebody use my old iPhone for them.
    How can I kill it? As I heard that IPhone 4s has that kind of function that killed all the pictures & data deleted as first initial time.
    Just let me know. I know my IMEI number and etc.

    It was not activated.

  • How can I find the Thread ID

    Hi
    I read the following sentences in FAQ:
    {forum:id=123} - Displays link to forum 123
    {thread:id=12345} - Displays link to thread 12345
    {message:id=1234567} - Displays link to message 1234567
    {user:id=1234} - Displays link to user 1234 (numeric ID)But I don' know where I can find the forum:id, thread:id and message:id
    Thank for your help
    hqt200475

    bigdelboy wrote:
    trent wrote:
    bigdelboy wrote:
    As far as I am aware the threadID and the messageID never appear in the same URL.At this top of this thread, there is a link for 'Last Post'
    This points to: Re: How can I find the Thread ID containing both thread and message id's
    In your example, the 'Whoever' bit is just plain text. i.e. no hyperlink (for me).
    I think you are talking about the links on the list of threads, whereas Aketi is referring to the link in the actual thread (at the top of the page).I feel a litlte outgunned {noformat};){noformat} ..... however I currently stand by my postulation their is no URL hyperlink where both the threadID (2234623 for this thread) and messageID (eg 9651344 for this post) are present in the same URL. URLs with the messageID obviously link to the thread on the basis the message is a child of the thread, but the threadID is not explicily present in this case.
    Rgds - bigdelboy
    http://en.wikipedia.org/wiki/A_Funny_Thing_Happened_on_the_Way_to_the_Forum ( {forum:id=29} )
    http://forums.oracle.com/forums/help.jspa
    Waht a plonker bigdelboy is!
    I think you are talking about the links on the list of threads, whereas Aketi is referring to the link in the actual thread (at the top of the page).I agree entirely. Apolgies to all. You are SO right.
    Permlink           Replies:  12  -   Pages:   1   -   Last Post:   Jun 10, 2011 8:23 AM  Last Post By: bigdelboy          Threads:  [ Previous |  Next   ]
    Re: How can I find the Thread ID

  • How Can I stop my thread?

    Hi!
    I'm developing an application of computacional geometry. It consist on a JFrame where I put some components like a JToolBar, a JTextArea, etc, and a JPanel. When the JPanel it's painted, there are a button that runs the JPanel in a new Thread.
    The problem is that I have another button to stop the thread, but I can't stop it completely if it is in a I/O operation.
    Here is the code of the run() method:
    public void run()
    Thread thisThread = Thread.currentThread();
    while (kicker == thisThread)
    if (runMode)
    lhull.removeAllElements();
         hull.removeAllElements();
    GrahamScan();
    runMode = false;
    aFrame.doneButton.setEnabled(true);
    stop();
    I stop the thread, but when it's in the GrahamScan() method, it continues painting things in the panel.
    How can I stop the thread completely?
    Thanxs in advance!!

    What's the matter with my line separators and my code indentation?
    Try to use yourThread.interrupt() at your button push event, and this code;
    public void run()
    Thread thisThread = Thread.currentThread();
    try {
    while (kicker == thisThread)
    if (runMode)
    lhull.removeAllElements();
    hull.removeAllElements();
    GrahamScan();
    runMode = false;
    aFrame.doneButton.setEnabled(true);
    stop();
    } catch (InterruptedException iEx){

  • How can I kill messages

    How can I kill messages with empty field: from < >?
    Some one have an idea?

    Also, a requirement for BATV to work correctly is that outbound mail from the internal mailserver going to the Internet needs to be relayed through the Ironport appliance to work.
    How can I kill messages with empty field: from < >?
    This would violate SMTP RFCs since mail systems MUST accept messages with an empty envelope sender. Check the Advanced User Guide, Chapter 2, Ironport Bounce Verification.
    If you turn on Bounce Verification (BATV), the appliance will 'tag' outgoing messages so that it will be able to recognize legitimate bounces and discard messages that appear to be bounces but did not originate on your system.

  • Jdeveloper threads?? how can I start a thread?

    Does anyone know how I can automatically set a thread in motion once I call a file in the project? I basically want a background process to run constantly while my app runs.
    Any thoughts??

    Try this:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html
    http://developer.java.sun.com/developer/Books/threads/chap9.pdf
    Linda
    null

  • How can i use multi threading in labview?

    i want to run a Digital storage oscilloscope and an energ ratio meter simultaneously using labview. i am using GPIB interfacing and windows XP. how can i do this using multi threading. Bot the instruments shd run and give data at the same time.

    You can't do this - at least not with a single GPIB board. It has nothing to do with threading or LabVIEW. There can only be one talker at a time over the bus. Depending on the instruments, you could probably set them up to take measurements simultaneously but you have to sequentially poll them to get the data.

  • How can I kill a OS process

    How can I get a handle to a OS process in my java application and then use that handle to kill the process.
    Note..that i want handle to a process which has not been started from my java application .

    It usually helps when you tell your OS whenever you need information about such an OS-specific issue. On Unix/Linux, you could just use one of Runtime's exec() methods and parse its output to obtain the process ID you are looking for.

Maybe you are looking for