How to stop a daemon Java Thread?

If I have a thread set as daemon and the main program has already exited, how do I locate the thread to stop it?
Thanks.

> As for stopping it you use a socket and send it a message. That of course would require another thread because it is a listener.
Could you explain me a little bit more this (or send a link)? That is probably what I want to do. I want to open another instance of the program and stop the running thread. (By the way I'm doing this on Windows).
Daemon thread != unix daemon.
I'm not actually setting the thread as deamon because I want it as a background task, but because I want the main program to exit after it has started the thread and I want the thread to keep running. I read somewhere that I could do this setting the thread as daemon. But I misunderstood what I read.
Again, what I want to know if there's a way of running an app that when you press a start button, for example starts a thread that performs some ops. and exits, but the thread is still running, and if you re-open the app and press the stop button it stops the running thread, that is, the instance of the app that created the thread is not the one who's going to stop it.
I don't necesarily want to do it using threads but that was the way I first thought of.
Thank you for your reply :)
Message was edited by:
daraii

Similar Messages

  • How to 'STOP' a running java thread in J2ME?

    Dear All,
    How to 'STOP' a running java thread in J2ME?
    In the middleware viewpoint, for some reasons we have to stopped/destroyed the running threads (we have no information how these applications designed).
    But in J2ME, Thread.destroy() is not implemented. Are there other approaches to solve this problem?
    Thanks in advance!
    Jason

    Hi jason,
    Actually there are no methods like stop() and interrupt() to stop the threads in J2ME which is present in normally J2SE Environment.
    But the interrupt method is introduced in Version 1.1 of the CLDC.
    So, we can handle the thread in two ways.
    a) If it is of single thread, then we can use a boolean variable in the run method to hadle it. so when the particular boolean value is changed , it will come out of the thread.
    for eg:
    public class exampleThread implements Runnable
    public boolean exit = false;
    public void run()
    while(!exit)
    #perform task(coding whatever u needed)
    public void exit()
    exit = true;
    b) If it is of many threads then we can handle using the instance of the current thread using currentThread() method
    for eg:
    public class exampleThread implements Runnable
    public Thread latest = null;
    public Thread restart()
    latest = new Thread(this);
    latest.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while( latest == thisThread )
    #perform some tasks(coding part);
    public voi d stopAll()
    latest = null;
    while ( latest == thisThread )
    performOperation1();
    if( latest != thisThread )
    break;
    performOperation2();
    Regards,
    Prathesh Santh.

  • How to stop rmiregistry through java coding?

    Hi,
    I don't know how to write java program to stop rmiregistry running on port 1099 ?
    Could anyone please help me?
    If possible please tell me the logic behind server shutdown program, like what we have in tomcat server, jboss etc.,
    Thanks and Regards
    Ram

    hi,
    Consider I'm working in the same JVM, I started rmiregistry using the command "LocateRegistry.createRegistry()". With respect to this scenario, please tell me how to stop the rmiregistry (say running on the port 1099)?
    Thanks and Regards,
    Ram

  • How to Stop the process of Thread

    Hi,
    A process is running in a thread, which will create a file with records in it.
    I have a cancel button and if I click the button, the process should be stopped i.e. it should not allow to create the file. Is it possible to do this?
    If so, how to achieve this? Please help me in this regard...
    Thanks in Advance

    Hi,
    A process is running in a thread, which will create a
    file with records in it.
    I have a cancel button and if I click the button, the
    process should be stopped i.e. it should not allow to
    create the file. Is it possible to do this?
    If so, how to achieve this? Please help me in this
    regard...
    Thanks in AdvanceThere is no (safe) way of just stopping the thread. What you can do is have a flag in your Runnable/Thread object that you flip when you click the Cancel-button. Then in your run() method you check every now and then if the flag has been flipped. If the flag has been set you stop what you are doing and do necessary cleanup.
    Something along these lines should do it (this is just a skeleton code that won't compile, but the general idea should hopefully be clear):
    class FileCreator implements Runnable {
        private File file;
        private boolean cancelled = false;
        // Method to call when you click the Cancel-button
        public synchronized void cancel() {
            cancelled = true;
        public void run() {
            // Do whatever it is you need to do. On suitable places in the code you check if
            // the job has been cancelled. E.g.:
            try {
                if( cancelled ) {
                    return;
                // Create the file
                file = new File(...);
                if( cancelled ) {
                    return;
                // Add the records to the file:
                for( Record rec : getRecords() ) {
                    if( cancelled ) {
                        return;
                    addRecordToFile(rec, file);
                // etc, etc
            finally {
                // Do necessary cleanup if the job was cancelled, e.g.:
                if( cancelled ) {
                    if( file != null ) {
                        // The file was created before the job was cancelled. Delete it:
                        file.delete();
                    // etc, etc
    // Somewhere else in your code:
    FileCreator fc = new FileCreator();
    new Thread(fc).start();
    JButton btnCancel = new JButton("Cancel");
    btnCancel.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            fc.cancel();
    ...Hope this helps!

  • 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 stop single VU, java-code

    Hi,
    Is there a way to stop a single VU?
    E.g:
    if (condition){
    stop iterating;
    Regards

    public void run() throws Exception
        boolean stopIt = false;          
        if (stopIt)
            IteratingVUser vu = (IteratingVUser) this.getScriptVUser();
            vu.stop();
            return;
    }

  • How to terminate a java thread from c++ code?

    Hi,
    I made a screensaver which loads a jvm, forks a thread running a java class, wait until user's action(i.e. mouse move/click keyboard input), then terminate the java thread.
    However, I met a problem, How to terminate a running java thread from c++ code?
    Here is my code, but it does not work: (even after the terminate is called, jvm throws an error)
    JNIEnv* env;
    JavaVM* jvm;
    HANDLE hThread; //handle for the startThread
    unsigned __stdcall startThread(void *arg)
         jclass cls;
         jmethodID mainId;
         jint          res;
         int threadNum = (int)arg;
         res = jvm->AttachCurrentThread((void**)&env, NULL);
    cls = env->FindClass( MAIN_CLASS);
         mainId = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         // setup the parameters to pass to main()
         jstring str;
         jobjectArray args;
         int i=0;
         args = env->NewObjectArray(1, env->FindClass("java/lang/String"), 0); //only one input parameters
         str = env->NewStringUTF("localhost");
         env->SetObjectArrayElement(args, 0, str);
         env->CallStaticVoidMethod(cls, mainId, args); // call main()      
         if (env->ExceptionOccurred()) {
                   env->ExceptionDescribe();
         return TRUE;
    Here is the main method:
    First create the jvm and load the thread. then tries to terminate the thread, but failed here
    switch (msg)
    { case WM_CREATE:
              JavaVMOption options[NUMBEROFOPTIONS];
              JavaVMInitArgs vmargs;     
              jint rc;
              vmargs.version = JNI_VERSION_1_4; /* version 1.4 */
              vmargs.options = options;
              vmargs.nOptions = NUMBEROFOPTIONS;
              vmargs.ignoreUnrecognized = JNI_FALSE;          
              rc=JNI_CreateJavaVM( &jvm, (void **)&env, &vmargs ); /* create JVM */
              /* We pass the thread number as the argument to the invoked thread */
              unsigned int threadId = -1;
              // to initialize a thread-safe C runtime library
              hThread = (HANDLE)_beginthreadex(NULL, 0, &startThread, NULL, 0, &threadId );
    } break;
    case (WM_DESTROY):
              CloseHandle( hThread );
              jvm->DestroyJavaVM(); /* kill JVM */
              Debug("Destroy Java Virtual Machine\n");
    }break;
    Note, after the thread "startThread" runs, it has an infinite loop and will not terminate, until the user clicks to terminate.(I didn't call jvm->DetachCurrentThread();_endthreadex(0); in the "startThread" because the java thread will not terminate by itself)
    Thus, the only way to terminate the thread is to call closehandle(hthread) in the main thread, which may cause jvm to throw an error.
    Do you know how to terminate a java thread safely???
    Thanks a lot

    Assuming that your java thread is in a loop of some kind. Such as
    int i=1; /* I tried using a boolean, I just could not get my C++ env, to change this value. So i decided to use an int */
    run {
    while(i)
    isdfjsdfj
    void seti()
    i=0
    So, B/4, i call destroyVM in my C++ code, i call this seti(). so the loop terminates, therefore my thread finishes executing and ends.
    Hope this helps
    tola.

  • How to use Java threads in ColdFusion

    Hello Everybody,
    I have a question in concerns to threads. We all know that in
    CF8 we have this fantastic tag called <cfthread> which give
    us the ability to create assyncronous code, however, I was
    concerned about earlier versions of ColdFusion, like CF7 and CF
    6.1.
    How can I create a Java thread and use it in my CF code?
    Please, any help is much appreciated. Thanks in advance.
    Alvaro Costa
    Systems Analyst
    [email protected]

    A bean is obtain by <jsp:useBean> tag nd once bean is obtained we can get its property by using getProperty tag.

  • !!!-Need help for terminating a Java thread in real time

    Hi everyone!
    I use J2SDK1.4.1 on a Unix platform.
    I want to terminate (or stop) a running java thread, which is dealing with time consuming tasks, in real-time (for example: the delay before the thread is terminated can't beyond one second), However, I don't know which techniques I can use to make sure the previous (or old) running java threads have been terminated?
    Could you please give me any help if you can?
    Any suggestion or reply will be kindly appreciated!
    Thanks!

    Thanks very much, jverd !
    I do set a flag that the thread should periodically check !
    Well, the scenario is like this:
    1. the thread read line by line (using BufferedReader) string from a probably huge-size file
    2. analyse each string read from the file if required (some strings may be omitted based on the user's operations), the analyzing process is a time-consuming task, and the analysing process may be terminated at any time the user want.
    3. record only the strings that have been analyzed by the previous process into a recording file
    The problem I meet is as follows: (Here, I suppose that it should take at least 30 seconds to finish analyse all the strings in a given huge file )
    1. the user start the analysing process, and run it for only 5 seconds,then stop the analyzing.
    2. the user start the analysing process again from the begining of the file(analyse the strings within the same file as previous step), and then stop the analysing process at 10 second. (it means, this time the analysing process is running for 10 seconds, still haven't finish analyse all the strings in the file).
    Once I open the record file, I saw some of the strings in the recording file have been repetitively record for 2 times, and the repetitive strings are just the strings the analysing time from at 5 second to at 10 second.
    And the repetitive times are depend on how many time the user start and stop the analysing process using the same file. for example, based on the above two steps, the user do the third step as follow:
    3. the user start the analysing process once again, analyse the same file,too. And run it for 15 seconds
    This time open the recording file, this time I saw some of the strings have been repetitively record for 3 times, and the repetitive strings are just the strings the analysing time from at 10 second to at 15 second.
    So, I guess the problem is probably because the previous analysing threads haven't been terminated completely, or say they just are blocked or set as inactive etc., then when the next time start the analysing process, the old threads will be reactive,and rerun ffrom the last time they are blocked.
    I hope you had catched what I mean, if you not, please ust let me know, I'll try to explain it again.
    Thanks once again!

  • How to stop a thread in java 5 for a real-time system??

    Hi,
    In Java 5, thread.stop is deprecated. We need to modify some variable to indicate that the target thread should stop running. "The target thread should check this variable regularly........"
    We are currently developing a simple real-time operating system using the basic features of java. It is running on top of SunSPOT (JAVA5). My question is I need to stop a thread in a scheduler loop of a real-time operating system. We cannot check it regularly. Otherwise it is not a real-time operating system.Is there anyway else to do this?
    Thanks,
    Qing

    That's rather hard to answer. You say you are writing in Java, but you're writing an OS. BUt what's executing the Java - you need a VM of some form. Is that a real-time or non-real-time VM? How it does things ultimately controls how effectively you can do what you are trying to do.
    The simple answer is that Thread.stop() is deprecated and that it will not stop a thread in all situations anyway - eg trying to acquire a monitor lock. But all Thread.stop does is make an exception pending on the thread, and as the thread executes it polls to see if there is an exception pending. When this happens depends on the VM: it might be after every bytecode; it might be when the thread transitions states (eg thread-in-java, thread-in-vm, thread-in-native) - it all depends. But it is polling - just the same as checking that variable - it's just implicit in the VM rather than explicitly in your code.**
    The RTSJ adds a new form of asynchronous termination requests through the AsynchronouslyInterruptedException (AIE). But it only affects code that explicitly declares that it expects AIE to occur, and there are also deferred sections where the AIE will remain pending. Writing code that can handle AIE is very difficult because the normal Java rules are "bent" and finally blocks do not get executed inside AIE-enabled code.
    So as I said this is very hard to answer, it really depends what exactly you are running on and what you are trying to achieve.
    ** Note: some people used bytecode rewriting tools to add this kind of polling as a post-processing step. Perhaps that is something you might be able to do too.
    David Holmes

  • How to stop the thread?

    Hi,
    How to stop the thread in java. This is my program.
    import java.net.InetAddress;
    public class ThreadPing extends Thread {
         ThreadPing(String pingIP)
              super(pingIP);
              start();
         public void run()
              try
              String pingIP = Thread.currentThread().getName();
              InetAddress inet = InetAddress.getByName(pingIP);
              Boolean get=inet.isReachable(1500);          
              if(get==true)
                   System.out.println(inet.getHostName());               
              }catch(Exception e)
         public static void main(String args[])
              for(int i=1;i<=100;i++)
                   String pingIP = "192.168.1."+i;
                   ThreadPing tp = new ThreadPing(pingIP);
    Thanks in advance.

    The simplest way to stop all the thread is to make all thread daemons and exit the program when you want them to stop.

  • How do i let a java process behave like a daemon process

    i want to make a java application that will start up and remain running so it can accept client connections and i also want to be able to have some sort of application to stop the daemon process.
    How do i go about doing this

    Your Java app needs to listen on a socket for an incoming "close" request. The Java app would then should down neatly (maybe by interrupting the main processing thread).
    You would then have to code a script which would send the appropriate close sequence to the socket. Look at some of the Java networking/sockets tutorials.

  • How to stop main thread ?

    Hi,
    Inside my java class, after I launch a GUI, I want to stop this main thread. After user make some choice and close GUI window, then, I want to go back to main thread. I use wait() method inside my class to stop main thread , but it does not work and it give me "IllegalMonitorStateException" error. I met same thing, when user close the GUI window and call method notifyAll(). How to stop main thread for a while and how to go back?? Thanks
    Gary

    Hi,
    you can create a boolean, and create a while loop, with a Thread.sleep(time); when you want to continue, you just have to change the state of your boolean. So you don't hava to exit the main. And you can't restart a run() in a thread. You can run it only once, so try to keep in your run() with an appropriate loop.
    Hope it helps.
    S�bastien

  • How to stop the java timer

    I tried writing a program for a scheduler using java , compiled and ran in java 1.6 .The code is given below
    import java.util.*;
    public class TimerTaskEx2 {
         public static void main(String[] args) {
              Timer timer = new Timer();
              timer.scheduleAtFixedRate(new TimerTask(){
                   public void run() {
                        System.out.println("Java");
              }, 5000, 1000);
    output
    Java
    Java
    Java
    Java
    Java
    Java
    Java
    The output of this program starts after 5 milliseconds delay and keeps running infinitely becoz the program is written only in such a way .
    but my actual requirement is the timer should start 5 milliseconds after i run the program and stop after 20 milliseconds .
    Here I need to know how to stop it at a required time interval
    I dont find any api regarding this in 1.6 spec .
    please clarify how to do that .
    Thanks
    Jee

    try this code:
    import java.util.*;
    public class TimerTaskEx2 {
         public static void main(String[] args) {
              Timer timer = new Timer();
              timer.scheduleAtFixedRate(new TimerTask() {
                   int i = 0;               
                   public void run() {
                        System.out.println("Java");
                        i++;
                        if (i > 3)
                             this.cancel();                    
              }, 5000, 1000);
    Also, make sure to close the alive thread too.

  • How to stop threads, process, streams when closing a (internal) JFrame?

    Dear all,
    I read a Javaworld article about Runtime.exec(), which will output the process outputs and error outputs to either a file or System.out. Now I want to practice it by outputing the process output/error to a Swing JTextArea. It works fine if the process ends successfully.
    My problem is that I want to stop all the output threads and clear all the streams when user click close JFrame button before the process finished. The code is shown below. Note that this frame is poped up by a click from another main frame. ( it is not exiting the main Swing application). This happened when I want to kill a process when it is running.
    I tried to implements a WindowListener and add
    public void windowClosing(WindowEvent e) to the JFrame.
    Inside this method I used process.destroy() and errorGobbler = null, outputGobbler = null, or outputGobbler.interrupt(), errorGobbler.interrupt(). But all these seems does not work. Sometimes thread was not stopped, sometimes process was not destroyed (because the stream was still print out something), sometimes the error stream was not successfully closed - by printing out interruptted by user error message.
    How can I make sure all the underlying streams and threads, including the PrintStream in StreamGobbler class are closed?
    Again this Frame could be a Dialog or InternalFrame, i.e, when I close the frame, the main frame does not exit!
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        OutputStream os;
        StreamGobbler(InputStream is, String type, JTextArea out)
            this(is, type, null, out);
        StreamGobbler(InputStream is, String type, OutputStream redirect, JTextArea out)
            this.is = is;
            this.type = type;
            this.os = redirect;
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    if (pw != null)
                        pw.println(line);
                    out.append(type + ">" + line);   
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe)
                ioe.printStackTrace(); 
    public class Test extends JFrame
        private JTextArea output;
        private StreamGobbler outputGobbler;
        private StreamGobbler errorGobbler;
        public Test (String file)
            super();
            output = new JTextArea();
            try
                FileOutputStream fos = new FileOutputStream(file);
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java jecho 'Hello World'");
                errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR", out);           
                outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT", fos, out);
                errorGobbler.start();
                outputGobbler.start();
                int exitVal = proc.waitFor();
                output.append("ExitValue: " + exitVal);
                fos.flush();
                fos.close();       
            } catch (Throwable t)
                t.printStackTrace();
         setSize(400,400);
         show();
    }Thanks !

    Thread.interrupt() doesn't stop a thread. You'll have to read the API for more specifics. You could use something like interrupt to force interruption of the thread for the reason of checking the terminating case though. I believe you would want to use this in the case where operations can take a long time.
    Setting your reference to the thread to be null won't stop the thread since it's running. You just lose your reference to it.
    I believe once the thread stops running your streams will be closed, but possibly not cleanly. Someone who has more knowledge of threads might be able to answer this better, but I would generally say clean up after yourself especially if you are writting out data.

Maybe you are looking for

  • MacBookPro - MiniDisplay to HDMI adapter to television - Live Stream

    I would like to watch hulu on my television through macbook pro. I already hooked it up through the minidisplay to hdmi converter. I have the purple space scene showing up on the television, but can't get anything else to play. I also tried to play a

  • T-code HRBEN0005 calling different form for open enrollment

    Hi, I have to create two different forms for different adjustment reasons for open enrollment(t-code HRBEN0005). But in the config table T74HL we can call only one form so I am looking for an enhancement where i can  pass the form name according to t

  • Help troubleshooting ORA-31003 when granting privilege

    Hi All I'm stumped on this. I need to enable network services for APEX_030200 using the script provided by Oracle. I've read many metalink docs and forums etc... Spent hours(days...) troubleshooting so any help would be greatly appreciated. We reload

  • Any new requirements for LS publish wizard in VS2013 update 4?

    Hi! Since I have some troubles when trying to publish my upgraded app (SL Desktop OOB) to win2012 server IIS, and customer service of that specific provider couldn't help, I'm gonna try to ask here..  So i have standard cPanel web interface, and in r

  • Difference betwen loading a repository and connecting to a repository

    Hi, In the MDM console i see 2 options. 1) Load Reposiotry 2) Connect repository. I mount the mdm server. then i mount the mdm reposiotry and connect to it. After connecting i am able to log into the data import manager and data manager and choose th