Stopping a simple Thread

I read the article http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html but it did not helped me much.
Here is a simple scenario that I'm unable to solve.
Consider a misbehaving thread:
public class Nano extends Thread {
     @Override
     public void run() {
          while(true) {
               System.out.println(System.nanoTime());
Assume that the class above is a third party tool and I cannot modify it. (Eg. I cannot add a flag to the loop like - while(keepRunning))
I create a class to run this misbehaving thread, and try to KILL it after a certain timeout:
public class MyThreadDemo {
     public static void main(String[] args) {
          Thread t = new Nano();
          System.out.println("Starting the new thread");
          t.start();
          // Some operation
          t.interrupt();
          System.out.println("Thread is now Stopped. Terminating Application.");
Well, the message "Terminating Application" is printed, but the thread Nano keeps running for ever.
Can you suggest a possible solution, a safe way to stop the thread?

837595 wrote:
I read the article http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html but it did not helped me much.
Here is a simple scenario that I'm unable to solve.
Consider a misbehaving thread:
public class Nano extends Thread {
     @Override
     public void run() {
          while(true) {
               System.out.println(System.nanoTime());
}Assume that the class above is a third party tool and I cannot modify it. (Eg. I cannot add a flag to the loop like - while(keepRunning))
I create a class to run this misbehaving thread, and try to KILL it after a certain timeout:
public class MyThreadDemo {
     public static void main(String[] args) {
          Thread t = new Nano();
          System.out.println("Starting the new thread");
          t.start();
          // Some operation
          t.interrupt();
          System.out.println("Thread is now Stopped. Terminating Application.");
}Well, the message "Terminating Application" is printed, but the thread Nano keeps running for ever.
Can you suggest a possible solution, a safe way to stop the thread?Run it in a separate JVM.
You want two threads in the new JVM.
One control thread that interacts with your original app in the original JVM.
One daemon thread that runs the misbehaving code.
When your original app in your original JVM tells the control thread in the new JVM to exit
there will only be a daemon thread left and the JVM will exit.

Similar Messages

  • Plz can someone show me simple thread code work

    Plz can someone show me simple thread code work with main function, without any applet...thread including start(),run(), and stop(), am I right or not ??
    thx

    http://java.sun.com/docs/books/tutorial/essential/threads/index.html

  • Stop an OSGi thread

    Hi everyone!
    I am programming a OSGi bundle using Eclipse. The problem is that I don't know how to use the stop method in the Activator class so my program does never stop and I have to stop it by hand. For example:
    public void start(BundleContext context) throws Exception {
          System.out.println("Starting bundle"); }
    public void stop(BundleContext context) throws Exception {
         }The console shows the Starting bundle message but instead of stopping the program after doing the only thing it must do, it does not stop. What should I write in the stop thread so that the program after showing the message stops?
    Thanks in advance!

    What exactly are you trying to do? Calling Thread.stop( ) is inherently a bad idea (see the Javadocs).
    You are getting a IllegalStateException because Thread.stop( ) kills the thread, you would need to create a new thread to resume execution.
    If what you are trying to do is pause execution, you probably want to redesign your thread's tasks into smaller chunks that can be launched separately. Alternatively, have the thread check it's interrupted state and if a flag was set block on a monitor until you want it to resume execution.

  • Cannot stop memory monitor thread

    Hi All,
    I am getting the following error intermittently in a dataflow which has degree of parallelism = 8.
    22943 0 SYS-170111 27/11/2009 12:22:05 |SubDataflow DF_Conform_ISI_Person_Match_Prep_1_9
    22943 0 SYS-170111 27/11/2009 12:22:05 Cannot stop memory monitor thread: <RWThreadImp::terminate - No thread is active within the runnable>
    Any ideas as to the cause ?
    Thanks,
    Eric Jones.

    We are having the same issue.
    According to ADAPT00890818, this issue should be resolved in 12.0.0. We are currently running with version 12.2.2.3.
    Please advice.

  • I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with emails from this thread. I used the action within the thread that says stop following but appears to have no effect I stil

    I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with  emails from this thread. I used the action within the thread that says stop following but appears to have no effect I still keep  getting from 5 to 20 emails daily. Please help!!!!!!!

    This may be helpful: How do I disable email notifications?

  • SYS-170111 - Cannot stop memory monitor thread: RWThreadImp::terminate -

    Hi Experts,
                  WE have this warning in pretty much every job in production. But the warnings are not specific to certain jobs they might occur one day and not the other day.
    Cannot stop memory monitor thread: <RWThreadImp::terminate - No thread is active within the runnable>.
    I know looking at the release notes this issue was fixed in 3.0 (12.0.0), we are using 3.2 (12.2.0) and having the same issues. The job server is on a linux 64 bit. I have not seen this issue in any of our windows job server. Is this bug specific to linux or is there a resolution for this.
    Appreciate your help in advance.
    Thanks
    AJ
    Edited by: alangilbi on Sep 28, 2011 5:17 PM

    Hi, AJ.
    As can be seen in the KBA 1455412 this is a known behavior.
    "As a result of fixing the problem identified in ADAPT 00890818 in release 12.0.0.0, this message is displayed by design. If there is really a problem in stopping the memory monitor thread an exception is thrown and an error message is logged.
    Background:
    In the memory monitor's shutdown logic, once it tells the monitor thread to shutdown it waits for the thread to terminate but only for 10 seconds. It could be that at this same time the wait expired when the thread actually terminates. So when this happens in the shutdown logic we force terminate the thread. Since there is no active thread anymore the terminate call throws an exception and then we catch it and then throws the error for the job."
    You can just ignore this warning.
    Leo.

  • How do I STOP & DESTROY a thread?????

    I cannot seem to get my wait cursor to work. Sometimes it appears, sometimes it doesn't. After searching the forums I saw that I must put my long computational code in a seperate thread to get my wait cursor to be painted...
    My question is: How do you stop & destroy a thread? Or will it automatically stop/destroy itself when done running?

    Currently, what I am doing is:
    //set cursor
    public void run() {
    //long process
    //set cursor to normal
    This seems to work fine, but I just wanted to make sure there is not stop/destory method. I didn't want 50 empty thread floating around. I am new to using threads...
    Thanks!

  • Stop the running Thread

    Hi
    i am calling the thread .in the midlle of running thread i have to stop the thread .please help me .
    my senario like . I am calling the scripts . i am wating certain period to complete the script exection . if the scripts are not available its still wating for a long time . so i am using the thread to execute the scripts and (main thread )checking each duration is completed or not . if the duration completed i am stoping the thread with Thread.Stop() method . but the thread still is alive . next time when i call Thread.Start() its throwing "java.lang.IllegalThreadStateException".
    please help me this .
    Thanks in advance
    public class TestCaseScriptProcessor extends Thread {
    public String execute(){
    TestCaseScriptProcessor caseScriptProcessor = new TestCaseScriptProcessor();
    caseScriptProcessor .start();// second time throwing java.lang.IllegalThreadStateException.
    while (!isExpired) {
    caseScriptProcessor.stop();
    public void run() {
    Edited by: 849614 on Jan 17, 2013 6:17 AM
    Edited by: 849614 on Jan 17, 2013 6:22 AM

    What exactly are you trying to do? Calling Thread.stop( ) is inherently a bad idea (see the Javadocs).
    You are getting a IllegalStateException because Thread.stop( ) kills the thread, you would need to create a new thread to resume execution.
    If what you are trying to do is pause execution, you probably want to redesign your thread's tasks into smaller chunks that can be launched separately. Alternatively, have the thread check it's interrupted state and if a flag was set block on a monitor until you want it to resume execution.

  • Stopping a blocked Thread

    I need to stop a Thread, or interrupt a blocked I/O.
    I'm making a call to a library that I do not own and cannot change. The library makes a HTTP connection to a service and waits for a response. As far as I know, the library uses BufferedReader to read the service response. If the service is down, then no response is ever returned, and the BufferedReader read simply blocks.
    I cannot change the library to be intelligent, of course, and don't have very good luck getting the service support to fix their stuff. But I have to use the library. How can I interrupt the blocked I/O read?
    What I've tried is as follows, but I'm not convinced it's the right way. My application is a long-running application that does not exit very often, so I'm concerned also about gc not properly recycling the resources due to still having the blocked thread still there (and this has impacted subsequent executions, even though I use local variables where I can).
            // Create a new Thread to wait on the submission
            Thread t = new Thread() {
                public void run() {
                    response = event.submit();
            t.setDaemon(true);
            t.start();
            try {
                t.join(timeOut);
                msg = "Attempt to connect to ESM Server timed out";
            catch (InterruptedException e) {
                msg = e.getMessage();
            }The other option I was thinking of, was coding my call to ESM server in a separate Class with a main, and invoking it via Runtime.exec. That way, at least I'm 100% sure that the code exits, and I can use System.out/err to receive the "output".
    Given that Thread.stop() is deprecated, and that you theoretically cannot interrupt blocked I/O, how have others solved this problem?
    Thanks,
    Matt

    ...you theoretically cannot interrupt blocked I/O, how have others solved this problem?I've done it your way. Each thread does an access. If it takes too long, then it may never respond and I ignore it. I also log the error condition and try to notify and administrator.
    Threads probably take up about a megabyte of memory so I may run out of memory it the problem doesn't get fixed by manual intervention.
    Your idea of using Runtime means that you create a new JVM for each ESM. If a thread takes up a megabyte, the new JVM takes up many, many megabytes. Instead of running out of memory in the JVM, you may run out of memory in the Box.
    Every situation is different. My thread approach works for my application. What works best for you is your call.

  • Stopping  a child thread

    Here is a class that will create a process thread. The process thread will talk to a database through another class.The process thread should return the result within *30* seconds.If it returns before *30* second it is fine. Help me how to stop the process if it takes more than 30 second.
    public class Details{
    //Method will return a Map
    public Map getDetail(String name){
    ProcessThread process = new ProcessThread (); //This is new thread
    process.setName(name);
    Thread t = new Thread(process);
    long initTime = 0;
    long startTime = System.currentTimeMillis();
    long sleepTime = 30000;
    t.start();
    try{
    //the process thread should return a Map with in 30 seconds.The current thread sleep for 0ne second and checks the time is exceeding *30* seconds and the process thread is still running.If the process thread returns before *30* second it is fine otherwise it shoild kill the process thread
    while (t.isAlive() && initTime < sleepTime) {
    initTime = System.currentTimeMillis() - startTime;     
    Thread.sleep(1000);
    if (elapsedTime >= sleepTime) {
    throw new Exception();
    }catch(Exception e){
    return process.getDetailsMap();
    Here a code for a process thread
    public class ProcessThread implements Runnable {
    private String name;
    private Map detailMap;
    public void run() {
    detailMap = //here code for calling a class that will connect to database and process the result and return a "Map" .This will return within 30 second.If not i have to stop this thread.
    setDetailsMap(detailMap);
    pubilc void setName(String Name){
    this.name = name;
    public Map getDetailsMap(){
    return detailMap;
    Edited by: ragavarnan_call_screen on May 27, 2008 11:46 PM

    First create a timer thread that fires after the time period and which can be cancelled.
    If it fires (hasn't been cancelled) then one of the following must occur.
    1. If and only if the driver/database is fixed and the driver supports the Statement.cancel() method then use it. You must test this and be sure to test for regular queries and procs as well.
    2. Close the connection.

  • Simple threaded job scheduler memory issues

    Hi,
    I'm working on a very simple job scheduler that triggers some processes to be run (based on a config file) and will spawn a thread to run the command every X number of seconds.
    My initial version of the code showed an obvious memory leak, starting at about 20MB usage and increasing after running overnight to about 80MB... I have since stripped down the program to a very minimal bit of code that will basically create 100 job objects and trigger threads on each of them to go way and run a Cygwin sleep.exe for 5 seconds and then return, once for each job every 15 seconds. After running the profiler with this within Netbeans, the VM Memory utilisation graph showed a very similar graph, and exhibited the same memory utilisation as my previous version.
    I've tried to tweak the code as much as I can with my level of knowledge, so now I'm hoping someone might be able to help out to see if there are any flaws in my code, or any improvements that I could make in order to resolve my problem?
    Below is the code for the 3 classes that I'm using:
    Main class:
    package javascheduler;
    import java.util.ArrayList;
    public class Main {
        private ArrayList<Job> allJobs = new ArrayList();
        public static Main instance;
        public static void main(String[] args) {
         if (instance == null) {
             instance = new Main();
         instance.loop();
        public Main() {
         // Create lots of jobs
         for (int i = 0; i < 100; i++) {
             Job j = new Job(i);
             allJobs.add(j);
         System.out.println("Created 100 jobs");
        private boolean loop() {
         // Main loop
         int i = 0;
         int x = 0;
         while (true) {
             x++;
             try {
              Thread.sleep(500);
             } catch (InterruptedException ex) { }
             i++;
             if(i >= 10) {
              Runtime.getRuntime().gc();
              i=0;
             for(Job j : allJobs) {
              long now = System.currentTimeMillis();
              // Jobs run every 15 secs
              if(now >= j.getLastRunTime() + 15000 && !j.isRunning()) {
                  j.runJob();
    }Job class:
    package javascheduler;
    public class Job {
        private NativeJob runningJob = null;
        private String command = "c:/cygwin/bin/sleep.exe 5";
        private int jobId;
        private long lastRunTime = -1;
        public Job(int id) {
         jobId = id;
        public void runJob() {
         System.out.println("runJob started" + jobId);
         lastRunTime = System.currentTimeMillis();
         runningJob = null;
         runningJob = new NativeJob(command,jobId);
         runningJob.start();
         System.out.println("runJob returned" + jobId);
        public long getLastRunTime() {
         return lastRunTime;
        public boolean isRunning() {
         if(runningJob == null) {
             return false;
         } else {
             if(runningJob.isRunning()) {
              return true;
             } else {
              runningJob = null;
              return false;
    }NativeJob class:
    package javascheduler;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class NativeJob extends Thread {
        String command;
        int jobId;
        boolean running = false;
        Runtime r = Runtime.getRuntime();
        public NativeJob(String command, int i) {
         super();
         this.command = command;
         this.jobId = i;
        @Override
        public  void run() {
         running = true;
             try {
              System.out.println("Running command " + jobId);
              Process p;
              p = r.exec(command);
              int returnCode = p.waitFor();
              p.getErrorStream().close();
                    p.getInputStream().close();
                    p.getOutputStream().close();
             } catch (IOException ex) {
              Logger.getLogger(NativeJob.class.getName()).log(Level.SEVERE, null, ex);
             } catch (InterruptedException ex) {
              Logger.getLogger(NativeJob.class.getName()).log(Level.SEVERE, null, ex);
             System.out.println("Finished command " + jobId);
             running = false;
        public boolean isRunning() {
         return running;
    }Thanks
    Adam

    Thanks ejp and sabre.
    I've made some changes to the code following your suggestions, and am now trying out jconsole on windows (rather than the Netbeans profiler).. I'll post back after I've had it running a little while.
    If you could take a quick look at the updates I've made that's be very much appreciated.
    Main class:
    package javascheduler;
    import java.util.ArrayList;
    public class Main {
        private ArrayList<Job> allJobs = new ArrayList();
        public static Main instance;
        public static void main(String[] args) {
         instance = new Main();
         instance.loop();
        public Main() {
         // Create lots of jobs
         for (int i = 0; i < 100; i++) {
             Job j = new Job(i);
             allJobs.add(j);
         System.out.println("Created 100 jobs");
        private boolean loop() {
         // Main loop
         int i = 0;
         int x = 0;
         while (true) {
             x++;
             try {
              Thread.sleep(500);
             } catch (InterruptedException ex) { }
             i++;
             if(i >= 10) {
              Runtime.getRuntime().gc();
              i=0;
             for(Job j : allJobs) {
              long now = System.currentTimeMillis();
              // Jobs run every 15 secs
              if(now >= j.getLastRunTime() + 15000 && !j.isRunning()) {
                  new Thread(j).start();
    }Job class:
    package javascheduler;
    import java.io.IOException;
    public class Job implements Runnable {
        private String[] command = { "c:/cygwin/bin/sleep.exe","5" };
        private int jobId;
        private long lastRunTime = -1;
        Runtime r = Runtime.getRuntime();
        boolean isRunning = false;
        public Job(int id) {
            jobId = id;
        public void run() {
            System.out.println("runJob started" + jobId);
            isRunning = true;
            lastRunTime = System.currentTimeMillis();
            try {
                Process p = r.exec(command);
                StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");
                StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUTPUT");
                errorGobbler.start();
                outputGobbler.start();
                int exitVal = p.waitFor();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            System.out.println("runJob returned" + jobId);
            isRunning = false;
        public long getLastRunTime() {
            return lastRunTime;
        public boolean isRunning() {
            return isRunning;
    }Edited by: Adamski2000 on Aug 2, 2010 3:12 AM

  • Stopping and Restarting Threads

    Please help!!!! I have a situation similar to the classic producer consumer but I need to be able to stop the producer and consumer for some time so I can change some parameters (for example increase the buffer size) and then restart them with the new parameters. Is this possible? If it is how would I go about it.
    Thanks

    just "kill" the thread by setting it's stop condition to true and then start a new one.
    i.e.
    public someClass extends Runnable{
    private boolean keepRunning = true;
    public void killMe(){
         keepRunning = false;
    public void run(){
         while(keepRunning){
                \\do some interesting things !!!
    }

  • Labview stopped executing mutli-threaded

    Hi I have a serious problem.
    I have created a windows keyboard hook DLL and I call this DLL from Labview. Now in labview there are 2 threads (2 completely separated while loops) one for ControlPanel and one for processing data.
    Now DLL works with events, so one of the DLL calls freezes the processing thread until there is data available.
    Now the ControlPanel thread does what it does and it doesn't care if the other thread is frozen.
    So until today everything worked perfectly. Now I'm not sure but it looks that since I've build an application (exe) the vi runs as single threaded VI. Now this means that as soon as the processing 'thread' is stopped the whole application really stops.
    Now does somebody knows how to force Labview to use multiple threads? As I don't want to write the whole VI again. And more I would really like to know this.
    Peace
    Waldemar
    Attachments:
    example.zip ‏112 KB

    Found the answer -> in Call Library Function window the function must be set to reentrant so that the Labview knows the function can be run in any thread.
    Peace
    Waldemar

  • Simple thread questions

    Hi
    I'm implementing a simple app with 2 threads:
    - Thread A creates thread B and then listens on a socket, waiting for a shutdown command.
    - Thread B executes some app specific processing until thread A notifies it to quit.
    My questions are:
    - How can thread A notify thread B that it should exit?
    - If thread B needs to exit (because some fatal error ocurred while doing its specific processing, how can it inform thread A that it should also exit?
    Thanks in advance!

    Have thread B execute within a while loop using a boolean initially set to true that is set to false by thread A to trigger a shutdown. Make thread A a daemon thread so it shuts down when no other threads are active.

  • (J2ME) Stopping a blocked thread

    In J2ME, receiving a datagram blocks the current thread until a datagram is received. I have created a thread that simply receives a datagram and then loops waiting for the next one. How do I stop the thread when it is blocking in datagram receive waiting for a datagram to come in? I am using the code on http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html for a reference, and it mentions calling Thread.interrupt() but this method does not exist in J2ME.

    I tried searching for any API on J2ME... it looked like there were a lot of different specifications, and in any case I never found any API docs.
    However, i did want to say this:
    In regular java, the way you would normally do this is (ThreadObj).interrupt(), but you said this didn't exist. Are you 100% sure?
    If that's not working, I have 2 other ideas:
    1. Thread.stop() - it has been deprecated and is not technically "safe" but it could probably work in a pinch.
    2. There is often a way to put a timeout on an inputstream. See if you can do that.

Maybe you are looking for