Killing an anonymous Thread

Hi,
The question is: How can we kill a Thread that we don't have any reference to it.
I have a "closed" jar which launches two threads that don't die after the function execution. I cannot kill the JVM by invoking System.exit[0].
Is there any possibility to access the Threads that are running in memory and kill them? If so how?

Hi ChuckBing,
Thanks for replying. Well, actually I think you missunderstood the problem. Let me give you an exemple:
public class Test {
     public static void main(String[] args) {
          (new DontKillThisAnonymousThread()).start();
          (new KillMeThreadLauncherThread()).start();
class DontKillThisAnonymousThread extends Thread{
     public void run(){
          try{
               while(true){
                    System.out.println("I want to live forever...");
                    //From this single line of execution
                    //how can I find another thread (an anonymous one) and kill it.
                    sleep(1000);
          }catch(InterruptedException e){
               e.printStackTrace();
class KillMeThreadLauncherThread extends Thread{
     public void run(){
          (new KILL_ME_AnonymousThread()).start();
class KILL_ME_AnonymousThread extends Thread{
     public void run(){
          try{
               while(true){
                    System.out.println("Are you able to kill me without killing the JVM...");
                    sleep(1000);
          }catch(InterruptedException e){
               e.printStackTrace();
}Thanks

Similar Messages

  • Killing a Swing thread

    Hello,
    How can I kill a Swing thread? For example the program below would never exit. Sure you can type System.exit(0) which would exit anything, but what are the other solutions?
    I tried putting chooser = null;
    System.gc();in the end of main() but this won’t work.
    To formulate my question better - how would I kill a thread I do not have complete command of (i.e. I can’t do usual do/while thread stopping)?
    Big thanks in advance.
    public class SwingLiveTest{
        public static void main(String[] args) {
            JFileChooser chooser = new JFileChooser();
            if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) return;
            File file = chooser.getSelectedFile();
            System.out.println(file);
            /*chooser = null;
            System.gc(); */

    You can't kill any Thread like this, at least not those where there is no method to call.
    It is possible to cause a Thread to stop, call the stop method, however this is not the recommended approach for very good reasons (Read the JavaDocs for java.lang.Thread.stop() method to see why.
    It should be possible, once you have obtained a reference to the Thread you wish to stop, to call interrupt() on that Thread.
    This is not guaranteed to work because you are dependent on the implementation of the Thread class you are manipulating or the Runnable that the Thread instance is currently running.
    There may be classes in the com.sun packages which can aid you with this problem, this is where Sun usually sticks undocumented implementation however these packages are not officially supported and there is no guarantee that classes you use in one VM are available in another, in particular when the VM you are using is not a Sun VM.

  • How can a thread kill another blocked thread?

    Hello All,
    As the title mentioned, lets say i have a main class in which i created a new thread but for some reason, this thread is blocked so i want to find a way to kill this thread from the main class (the interrupt function is not working), is there a workarround to do this?
    Thank you in advance

    Hello,
    First of all, thanks for you interventions, i think i should clearify my case:
    I have a website which has a "Search the site" feature where a user can search the site for specific keywords
    The search engine is an external jar which we use by calling its API, but for some reason this search engine becomes blocked sometimes so my jsp which is calling this API gets also blocked and any subsequent search gets also blocked in the end the number of java threads becomes very high in my system!
    i want to find a way so that if the piece of code calling the search API didnt get excuted during a specific period, i want to kill the thread calling the search API
    lets say the search form is submitted to the following jsp
    // Here we have a SearchThread extends Thread
    /* i launched a new Thread to do the search independatly from the main process*/
    SearchThread task = new SearchThread("search_input");
    task.start();
    /* In the searchThread class we have a run method containing the following line which calls the search API, for some reason , this line never returns and keeps the thread in Running state and so the run() method never returns and so the thread will neve be dead :( */
    SearchLoginSession = new SearchLoginSession (configFile, true);
    Notes:
    1) the stop is deprecated i cant use it
    2) the suspend method will suspend it and not kill it, the thread will remain in memory
    3) the interrupt method didnt work
    4)i am working in a multi-cpu environment
    Finally , what i want is to find a way to remove this thread from memory from the main jsp listed above like
    task.kill() or some workarround
    Thank you for reading and hope you can help me

  • Can a parent thread kill a child thread?

    I'm writing a multi-threaded application in which it is possible for one of the threads to go into an infinite loop. Is there any way for a parent thread to actually kill the child thread that has gone into the infinite loop? Of course the parent thread won't actually be able to discern whether or not the child thread is in an infinite loop. I would specify some time out value, and when it has been exceeded, then I would want to kill the child thread. Is this possible without setting any sort of flag that the child would read, because once it gets stuck inside an infinite loop, there will be no way to read the flag.

    Here's an example of a program that I wrote to simply ping a server. It works somewhat backwards from what you were looking for (the child interrupts the parent) but should provide some clue:
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    public class ServerPing extends Thread {
      String [] args;
      public static void main(String[] args) throws Exception {
        ServerPing sp = new ServerPing(args);
        sp.start();
      ServerPing(String [] args) {
        this.args = args;
      public void run() {
        Pinger pinger = new Pinger(this);
        pinger.start();
        try {
          sleep(30000);
        catch (InterruptedException x) {
          System.exit(0); // this is ok. It means the pinger interrupted.
        System.out.println("TIMEOUT");
        System.exit(1);
    class Pinger extends Thread {
      Thread p = null;
      Pinger (Thread p) {
        this.p = p;
      public void run() {
        try {
          URL simpleURL = new URL("http://localhost:7001/ping.jsp");
          BufferedReader in = new BufferedReader(new InputStreamReader(simpleURL.openStream()));
          String inputLine;
          while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
          in.close();
          p.interrupt();   // <<-- interrupt the parent
        catch (Exception x) {
          x.printStackTrace();
    }

  • Can't kill a running thread...

    I'm having some problems killing a thread. Becuase thread.stop() is no longer used, I basically set a flag to tell all the threads to return by checking this flag in the run() method. The problem now is that there is a thread that is getting "stuck" in a class that I have no access to. So basically I assume that its a really long loop, or an infinite loop... either way, that thread doesn't stop even if the "parent" (spawning) thread is "stopped". Any suggestions?
    -L

    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?

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

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

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

  • 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

  • Wake up, wait, and kill one / many threads

    Hello all.
    I am trying to do something that I originally wanted to do with multicasting, but in the end could not.
    Essentially I want to create a bunch of threads, one for each machine I want to 'ping' (not the actual ping, just some kind of 'are you alive?'). These threads will just sit there and wait upon creation.
    Then when a request comes in I want to:
    1. wake them all up so they all send a 'ping' to their respective server.
    2. retrieve the ip address (or name) of the first thread that replies
    3. kill the rest of the threads (if they haven't already died)
    4. go back to waiting
    I've been surfing Google, Java tutorial and these forums and can't seem to put it all together.
    Many thanks for any help!
    Bob

    Hello again, thanks for all of the responses.
    I feel like a bit of a schmuck, I had no idea J2SE 5.0 had all of this new concurrency stuff. All of these things -- Semaphores, CountDownLatch, etc. -- are new to me. I've been trapped in the web / MVC world too long. I've used threads in the past but only for simple stuff, always trying to avoid all the messy stuff like synchronized blocks, wait(), notify(), etc.
    So I am boning up on all this new stuff now, thanks.
    As for you comment, 'I don't see the point in terminating them if you are going to repeat the exercise.', you're right, I didn't mean kill the threads that didn't reply first, I meant ignore them.
    Basically I have a situation where I'll have something like 60 requests per minute on average. For each request I want to wake up all the threads, send out a ping and send the request to the ip address of the first thread that replies.
    The problem of course is that during that one request I may have another, and another, since a ping could take anywhere from less than a second to 5 seconds to timeout. So, for example, If another request comes in while 3 out of the total of 5 threads are still pinging, only 2 will be woken up to send out another ping, and so on.
    It's complicated and it would be a lot easier with a simple multicast message using JGroups or a simple Java multicasting. But alas since these servers that I'll be pinging aren't ours, I can neither install a small multicast listener program on them or even be sure multicasting (port 124.0.0.1) is enabled.
    So that's the deal. I'm going to keep reading. Thanks for all of your help!
    Bob

  • Kill all childen threads on close?

    In my jfx2 app I have a thread that gets stood up. When I click the [X] for the main application window I want all "child threads" to be killed. Is this possible? I have not seen anything in the tutorials to describe this nor a way to override a "onClose" like method? Any help would be great.
    Riley

    Use childThread.setDaemon(true) for all child threads:
    (http://www.jguru.com/faq/view.jsp?EID=43724 "What is a daemon thread? When should I use setDaemon() and why?")
    If it is not possible to use a Daemon thread, implement logic in an onHidden event handler to notify the threads that they need to shutdown, implement logic in the threads to handle the shutdown notification, and join to each of the threads to await their completion or use a CountDownLatch. If you do this you might want to do the join or CountDownLatch wait in it's own seperate shutdown thread so as not to block the JavaFX application thread.
    http://docs.oracle.com/javafx/2.0/api/javafx/stage/Window.html#setOnHidden%28javafx.event.EventHandler%29
    http://javahowto.blogspot.com/2007/05/when-to-join-threads.html
    http://javahowto.blogspot.com/2011/08/when-to-join-threads-with.html
    Or, if there would be no adverse consequences, you can just call System.exit as aidreamer suggests.

  • How to kill a dead thread

    How to stop the following thread?
    class MyThread {
    public void run() {
    neverReturn(); //no kidding, happend to me
    private void neverReturn() {
    while(true)
    seems to me that "stop" is only way to go, right?
    Fei Li

    My question is: If I am not able to fix that bug (for
    example: call a third paty library) can I stop the
    thread without using stop?No.
    But if this 3rd party library runs into a never-ending loop, why would you continue to use it (if you have another choice)? However, I know of what you speak - even Sun's own classes (URL/URLConnection) can lock up. But the bottom line is, "garbage in, garbage out". The root of the problem (infinite loop) still needs to get fixed or all you're doing is writing band-aid hacks to work around it.

  • System.exit() didn't kill all the threads it spawned in Linux

    Facing problem while doing System.exit(0);
    Even though it is happening inconsistently but this how it is-------.
    The main application has spawned some threads.
    On receiving a particular event it interrupts all the threads and calls system.exit(0).
    Each thread after catching interrupted exception sends a interrupt to itself.
    What I'm observing is, once in a while the spwned threads are still hanging even though the application has exited.
    I'm having
    1) java version "1.4.2_04" and
    2) Linux 2.4.21-27.EL

    After writing Java code for 6 or 7 years, then having a years break and writing C++
    and D code. I came back to Java and am having the same problem as you.
    The cause of my problem was that I was writing the wrong code lol I was
    trying to use an ActionEvent instead of a WindowEvent ie:
    Im on Slackware btw. (nothing but the best )
    PS. I have also noticed that MPlayer does the same thing when you close it down.
    you can see it in the System processes still running. I havent looked at their
    code though.

  • Launching two thread and killing the original thread

    I'm having problems developing my application.
    Hi,
    I'm running and application wich has to self-update periodically. the way it's done is that i launch a different project, included in a different jar file. This project downloads an update for the application and relaunchs my application.
    At first, i did that change of application using a process wich executes the update jar (using getRuntime.exec()), but it looks that once launched the process, my application waits until the update jar is finished.
    I've thought to use parallel threads, i mean, my application is running on a thread, if update is necessary, then i create a thread wich executes the update jar and, once the download and update have been completed, create a new thread with my updated application, finishing the update thread after launching it.
    Do you know if, once updated my application's jar, the new thread will be executed with my updated code?
    I hope somebody can help me, thank you

    well, on my computer works, but it has to work in the end on a PDA with a customized jdk from java 1.3, so i'm not sure yet if it works fine. Once i have done it, i will tell you

  • Killing an Updater Thread when I stop watch an JPanel

    Hi,
    Firstly this is proably really bad code convention. What I am wondering is how to fix my problem and perhaps some guidance on what to do instead, I am unsurre as to how to model an Updater thread on a JPanel. What I am doing is updating the Icons in JTree when the data changes, this happens continally so there is no start finish defined.
    I thought I could use isVisible() to work out when to terminate my updater thread, ut that doesnt seem to be the case. Any Ideas on what to do???
    Thanks a Mill,
    Anthony
    public class MyTreePane extends TreePane {
         private boolean start = true;
         public XRiskHistoTreePane() throws Exception {
              super();
          * This threads jobs is to scan the
         private void startScannerThread() {
              Runnable  r = new Runnable(){
                   public void run(){
                        int [] keys = getRiskKeys();
                        while(isVisible()){
                             for(int i = 0; i < keys.length; i++){
                                  try {
                                       Reporter rep = UpdateClient.getPosition(keys);
                                       PercentageIcon icon = null;     
                                       if(rep != null){
                                            int per = (int) rep.getPercentage();
                                            icon = new PercentageIcon(per);
                                       setImageIcon(keys[i], icon);
                                  } catch (Exception e) {
                                       e.printStackTrace();
              Thread t = new Thread(r);
              t.setName("Update Thread");
              t.start();
              t.setPriority(Thread.MIN_PRIORITY);
         public void paint(Graphics visible){
              super.paint(visible);
              if(start){
                   startScannerThread();
                   start = false;

    Hi,<br> Firstly this is proably really bad code convention. What I am wondering is how to fix my problem and perhaps some guidance on what to do instead, I am unsurre as to how to model an Updater thread on a JPanel. What I am doing is updating the Icons in JTree when the data changes, this happens continally so there is no start finish defined. I thought I could use isVisible() to work out when to terminate my updater thread, ut that doesnt seem to be the case. Any Ideas on what to do???
    <br>
    Thanks a Mill, Anthony
    <pre>
    public class XTreePane extends TreePane (which extends JPanel) {
         private boolean start = true;
         public XTreePane() throws Exception {
              super();
         * This threads jobs is to scan the
         private void startScannerThread() {
              Runnable r = new Runnable(){
                   public void run(){
                        int [] keys = getKeys();
                        while(isVisible()){
                             for(int i = 0; i < keys.length; i++){
                                  try {
                                       Reporter rep = UpdateClient.aggregationPosition(keys);
                                       PercentageIcon icon = null;     
                                       if(rep != null){
                                            int per = (int) rep.getPercentage();
                                            icon = new PercentageIcon(per);
                                       setImageIcon(keys[i], icon);
                                  } catch (Exception e) {
                                       e.printStackTrace();
              Thread t = new Thread(r);
              t.setName("Update Thread");
              t.start();
         public void paint(Graphics visible){
              super.paint(visible);
              if(start){
                   startScannerThread();
                   start = false;
    </pre>

  • Kill/stop hung thread to generate an exception

    In production certain requests cause the thread executing them to hang. We are unable to reproduce that problem outside of production. One thought I had was to call stop on the thread executing that request which should cause a ThreadDeath which should be logged by our application so I could hopefully find the source of the problem. I made a way to call stop on a Thread and that seems to cause the Thread to die on my machine but not production. Any suggestions on that tactic or on a better tactic to use?

    See http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20599112.html for the resolution.

  • Anonymous Thread

    I have a checkbox . When i check one box and submit the page . It goes to Action where i take it using getParamterValues , but the for loop going twice some times . sometimes it goes to the jsp and comes back to the Action page again . i Have the stack Trace to show you
    The Length:1
    (IControlDAO) Inside the Item getRawProductList
    ---------------------Inside Excess Quantity Check-----------------
    Tha value of the checkBox is:151
    Checked Length:1Iteator Value0
    The Applied Value is:6
    (IControlDAO) Inside the DAO ItemQuantity List
    EXISTING Quan:0
    Quantity of picked Case:4
    The value of the Ein :800800802
    Screen : /CasePick.jsp?picked=ExcessVal
    (IControlDAO) Inside the Item getRawProductList
    Action : IControl
    (control)The Value of Emp ein -------800800802
    (IControlDAO) Inside the DAO getLoginDetails
    desk:10Desg:1privilege:11
    desk:10Desg:1privilege:11
    (Controller1)The value of the desk of the Login USer:10
    /AdminAction
    Event : ItemRecordSelect
    (IControlDAO) Inside the DAO ItemCombo List
    (IControlDAO) Inside the Item Delievered Updation
    The value of i:0
    (IControlDAO) Inside the Item getPickDetailsReportForm
    (DAO)The Value of the appliedDate:-----------:2008-04-02 12:03:53.0
    (DAO)The Value of the appliedDate:-----------:2008-04-02 12:03:53.0
    (DAO)The Value of the appliedDate:-----------:2008-04-02 12:03:53.0
    (IControlDAO) Inside the Item getRawProductList
    The value of the Ein :800800802
    Screen : /CasePick.jsp
    (IControlDAO) Inside the Item getRawProductList
    The Value of the Datee:2008-04-02 12:03:53.0
    (IControlEndUserDAO) Inside the DAO Excee Purchase Order List
    -----------------------Not Approved Done for Any condition---------------
    The Value of the Datee:2008-04-02 12:03:53.0
    (IControlEndUserDAO) Inside the DAO Excee Purchase Order List
    -----------------------All Quantity Approved---------------
    The Value of the Datee:2008-04-02 12:03:53.0
    (IControlEndUserDAO) Inside the DAO Excee Purchase Order List
    ----------------------- Available & Approved & display Remaining Quantity--
    ------------------------HERE THE Jsp Page finishes and this goes again to Action -------------
    Action : IControl
    /AdminAction
    Event : ItemRecordUpDate
    GMT+05:30
    Today : 04-02-2008 12:24:16
    The Length:1
    (IControlDAO) Inside the Item getRawProductList
    ---------------------Inside Excess Quantity Check-----------------
    Tha value of the checkBox is:151
    Checked Length:1Iteator Value0
    The Applied Value is:6
    (IControlDAO) Inside the DAO ItemQuantity List
    EXISTING Quan:0
    Quantity of picked Case:4
    The value of the Ein :800800802
    Screen : /CasePick.jsp?picked=ExcessVal
    (IControlDAO) Inside the Item getRawProductList
    Action : IControl
    /AdminAction
    Event : ItemRecordUpDate
    GMT+05:30
    Today : 04-02-2008 12:25:59
    The Length:1
    (IControlDAO) Inside the Item getRawProductList
    ---------------------Inside Excess Quantity Check-----------------
    Tha value of the checkBox is:151
    Checked Length:1Iteator Value0
    The Applied Value is:6
    (IControlDAO) Inside the DAO ItemQuantity List
    EXISTING Quan:0
    Quantity of picked Case:4
    The value of the Ein :800800802
    Screen : /CasePick.jsp?picked=ExcessVal
    (IControlDAO) Inside the Item getRawProductList

    The page has been submitted twice .

Maybe you are looking for

  • What is the best way to back-up my libary?

    Hi, I have just bought an external hard drive and am backing-up my Mac. I can see that I can use Aperture to back-up my photo's or I can simply use the LaCie back-up software that came with the drive. The LaCie software just dumps a copy of my home d

  • After Effects and Bridge error message

    After Effects error: Can't import file-.unsupported filetype or extension, (0 ::1) this happens when I double click on a text animator in Bridge. Started happening after I upgraded to After Effects 2014, anybody know how to fix this?

  • Billing release to accounting error

    Dear experts, Because profit center couldn't be carried into billing from Outbound deliv.  then while relasing billing to accounting ,it tips error message. Thanks.

  • You may need to restart

    I have a G5 running 10.4.6 After a few minutes, the box locks up and I get a box that says you may need to restart your computer. THe drive appears to be good, as I bit it in an Intel Mac and I can pull off it. Obvoiusly, it will not boot in that mac

  • Question about searching in finder.

    I updated to Lion which is much more annoying than the previous versions.  When searching in finder, how do I get it to search everything inserted of just the file name.  When I type something in it defaults to "Filename Contains XXXXXXX".  And every