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.

Similar Messages

  • How to kill thread

    I am facing the problem in killing the thread after some interval. If anybody knows how to kill the thread in middle plz give me reply
    Thanks
    Sreedhar

    Thread.interrupt()
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thre
    ad.html#interrupt() is not about killing or stopping
    a thread. It is more about kicking a blocked thread.
    There is no way to kill a thread. As been said
    above, the thread should be designed to accept
    instruction to stop gracefully.
    The interrupt() was created by sun as a solution sun came up for the problems of thread stop(), it should be the cannonical way to stop a thread.
    The problem with having your own mechanism of interrupting a thread is that you should have a method to interrupt a thread execution and a flag that should be checked from inside your thread or runnable code to see if it should stop and if so, do it cleanly. The problem with this aproach is that if the thread is sleeping or in some blocked state, calling your own interruption framework is inefective, as it could never get a chance to run the code.
    To solve that, sun privides us with the method( interrupt() ) and the flag ( Thread.interrupted() ) with the advantage that on calling it, it guarantees you that it would take effect even if the thread is in a blocked state.
    So, you are right about having to implement your own gracious interruption but the right way to do that is by checking interrupted(). And no Thread.interrupt() is not just about blocked threads, although it covers that ground.
    May the code be with you.

  • 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

  • How to kill parent and child thread in sequnece

    Hello freinds,
    I have one class FirstClass which creates one thread Pserver and Pserver creates three threads then how to kill parent Pserver and child threads.........

    define a method that requests that the parent thread terminate itself, and within the code called when the thread is shutting itself down, have it do something similar to its child threads: call methods that request they shutdown themselves.
    One common way to do this is to interrupt the thread.

  • How to kill threads in obiee server

    Can some one please tell me how to kill threads in OBIEE server

    944632 wrote:
    Thanks for the prompt reply. your answer is helpful. Here is my problem.
    I am an OBIEE admin and getting lot of complaints fronm developers that BI Server services are not stopping. I was adviced by my senior that i have to kill thresads in the server.
    I followed what you told but when i open the RPD, i am unble to open cache in either offline or online modeHi,
    - Unable to open cache due to you already disabled cache (usage tracking - nqsconfig.ini file) cache diabled that why you can't able to open cache
    just make sure
    [CACHE]
    ENABLE = YES;
    C:\Oracle\Middleware\instances\instance1\config\OracleBIServerComponent\coreapplication_obis1 (obiee11g file path ref)
    - unable to stop biservices? if that case you can kill it different ways, (stop bi services/ctrl +c on services/task manager/FMW (console/EM)/ services.msc etc) which way did you tried?
    (which version did u tired)
    Thanks
    Deva

  • Thread: How to tell when the thread is finished AND how to kill it?

    Hi there,
    I have a thread that runs in the background and does this:
    class MyThread implements Runnable 
              public void run()
                   Stopper stopper = new Stopper();
                            //do something that takes some time
                            stopper.stop();
                            System.out.println("total time "+stopper.getTime());
    }this works fine (I have a swing gui where I click a button and this thread runs and it's ok. PROBLEM IS, when I click the button again (to re-activate the thread) it seems that the stopper is not null but still counting the time (I was under the impression that ...= new Stopper() will create a new object type Stopper).
    so -
    1. How can I tell when thread is finished?
    2. How do I kill this thread once it is finished?
    the invocation:
         public void actionPerformed(ActionEvent arg0)
              Thread t = new Thread( new MyThread());
              t.start();          
         }THANK YOU!

    You have not posted to code for Stopper, so it's impossible to reason about that
    1. How can I tell when thread is finished?
    Use Thread.Join() or Thread.isAlive()
    2. How do I kill this thread once it is finished?
    You can't and you don't. Just let the method the thread is running exit normally. Sometimes that means putting in a boolean variable to control a loop, and then exiting when the boolean is false.
    Another thought - you could set the thread as a Daemon thread - when you don't have any non-daemon threads running, java will exit.

  • How to Kill Specific Execute Threads

    Hi.
    Through our application server, we noticed that there were some memory issues
    where the memory usage would rapidly increase from ~ 15Mb to the max heap size.
    Issuing a few thread dumps, we realized that there was a specific thread that
    was churning. This was b/c someone sent a large request in that generated a lot
    of data.
    Anyways, since we couldn't bounce the weblogic server, we had to wait until the
    request ended. Since we know the specific thread that was assigned to that job,
    is there a way to kill the request associated with a specific execute thread and
    reallocate back to the thread pool? We're running weblogic 6.1sp4. I think the
    executequeueruntime bean just gives me back the current configuration of the all
    the threads in the specific queue, which doesn't help me here.
    Thanks.
    --Selena

    Selena,
    how about get the ExecuteQueueRuntimeMBean and get all the execute
    threads (getExecuteThreads() which returns an array of ExecuteThreads )
    and since you know the thread id that is causing the bottleneck, you
    could kill that thread.
    thanks,
    -satya
    Selena wrote:
    Hi.
    Through our application server, we noticed that there were some memory issues
    where the memory usage would rapidly increase from ~ 15Mb to the max heap size.
    Issuing a few thread dumps, we realized that there was a specific thread that
    was churning. This was b/c someone sent a large request in that generated a lot
    of data.
    Anyways, since we couldn't bounce the weblogic server, we had to wait until the
    request ended. Since we know the specific thread that was assigned to that job,
    is there a way to kill the request associated with a specific execute thread and
    reallocate back to the thread pool? We're running weblogic 6.1sp4. I think the
    executequeueruntime bean just gives me back the current configuration of the all
    the threads in the specific queue, which doesn't help me here.
    Thanks.
    --Selena

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

  • How to "kill" AWT Event Queue thread without using System.exit()?

    When I run my program and the first GUI window is displayed a new thread is created - "AWT-Event Queue". When my program finishes, this thread stays alive and I think it causes some problems I have experienced lately.
    Is there any possibility to "kill" this thread without using System.exit() (I can't use it for some specific reasons)

    All threads are kept alive by the JVM session. When you use System.exit(int) you kill the current session, thus killing all threads. I'm not sure, though...
    What you could do, to make sure all threads die, is to make ever thread you start member of a thread group. When you want to exit you app, you kill all the threads in the thread group before exit.
    A small example:
    //Should be declared somewhere
    static ThreadGroup threadGroup = new ThreadGroup("My ThreadGroup");
    class MyClass extends Thread {
    super(threadGroup, "MyThread");
    Thread thread = new Thread(threadGroup, "MySecondThread");
    void exit() {
    //Deprecated, seek alternative
    threadGroup.stop();
    System.exit(0);
    }

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

  • How to Kill a Stored Procedure?

    Sombody knows how to kill a stored procedure from another stored peocedure?
    I wanna know if exists a way to use therads in sored procedures.
    Best Regards

    1) You can't. Unless you code a mechanism yourself, but then since
    you can't thread Procedure calls that wouldn't help much.
    2) You can try using DBMS_JOB, if your not in a hurry to have your procedure finish.
    This is PL/SQL, not Java. You have to imagine all you get is a single thread running
    static methods. You can get away from everything being static by using the CREATE TYPE
    OBJECT stuff. but that doesn't help you thread your processes.
    I hope someone else can give you a different answer,
    Eric Kamradt

  • How to kill Active Data Request in DSO

    Hi all,
    I have 2 dsos ( A, B). Data loads from A to B.
    Now I have deleted data from DSO B by using option delete data ( did killed one running request by turing the status to RED).
    when I try to load data again to DSO B, it is not allowing me to execute the DTP.
    Message is Request 257.617 is stil processing.
    I am SAP BI 7.0 environment.
    Please suggest how to kill active request ( I am not seeing it RSMO/SM37).
    I tried to use Zombie Request FM, it didnt worked.
    Thanks All,
    Jason

    Srinivas,
    Thanks for the reply.
    When I go RSRQ
    I can see the request , the exception it is showing is CX_RS_FAILED logged.
    SM51, when try to kill the process it says
    SAP System Message:
    Work Process restarted; session terminated
    Apologies for earlier post messages saying that I did nt saw the message in RSMO, I can see it is in yellow process.
    Please suggest how to kill the processes .
    Apperciate your response..
    Thank you
    Jason

  • How to kill a job in SM37

    hi All,
             can someone wxplain me how to kill a job in SM37 which is delaed by 10,000 secs.
    cheers

    Hi Rase,
    goto SM37 and click on the active selection and enter the jobname and then click excute the particulr job should appear highlight the jobname then click on the stop iconthat appears on the taskbar( 3 rd from left)
    or goto SM50 Click on the process and select process->stop without core
    or
    set a running infopack of the chain (in RSMO) to red, thats will stop the chain (if there are no parallels, else set all parallels to red).
    ****Assign Points If Helpful****
    Regards,
    Ravikanth

  • Cant sync my iphone contacts with yahoo, it says "unknown error (4)" and tells me to come back later, been doing it for months. Any ideas on how to kill it?

    cant sync my iphone contacts with yahoo, it says "unknown error (4)" and tells me to come back later, been doing it for months. Any ideas on how to kill it?

    Hey joshuafromisr,
    If you resintall iTunes, it should fix the issue. The following document will go over how to remove iTunes fully and then reinstall. Depending on what version of Windows you're running you'll either follow the directions here:
    Removing and Reinstalling iTunes, QuickTime, and other software components for Windows XP
    http://support.apple.com/kb/HT1925
    or here:
    Removing and reinstalling iTunes, QuickTime, and other software components for Windows Vista or Windows 7
    http://support.apple.com/kb/HT1923
    Best,
    David

  • How can I see how many replies a thread has?

    The old layout let you see how many replies a thread had. Is there any way to get that back?

    To the end of the URL of a discussions page, add:
    /content
    ...In the resulting page, click on the big Discussions tab and then bookmark that URL. Here's a screenshot:

  • Maybe you are looking for

    • How to change language in speak selection

      Hello! Once i bought my fourth gen ipod touch, default voice in "voice over" and "Speak selection" was British Eglish. Some day i had to restore my ipod,and i did, after that default language was US English with female voice! I found out how to chang

    • Best way to determine if JMS server is alive in a cluster

      Can anyone give me an idea on the best way to find out if a JMS server           in a cluster           has failed so I can signal migration to another server in the cluster.           Thanks Larry           PS weblogic 7.0 sp1           

    • Can't open some web pages

      Hi, can anyone help me with my problem, when i try to surf the ner some pages give me this notice that i need to have explorer 5 or upper grades of explorer. what should i do?

    • Connecting external swf files to a main home page swf.

      Hi, sorry I realise theirs a few questions like this already out there, but I just cannot find the information I need with them. I have a home page in that their are 4 buttons which lead to 4 different pages, I essentially need mine to be able to cli

    • Downgrade from Leopard to Tiger? Help please

      I just got a new iMac that came with Leopard and I'm planning to use it soley for pro tools and pro tools isn't yet compatible with Leopard so I would like to downgrade to Tiger. How can I do this? I just ordered 10.4.8 for iMac's but am not sure if