Stopping A thread

HI,
I have written an application which starts two threads. Later on i want the two threads two stop using another method call.
Actually i am starting the threads calling a bean from my JSP. Now i want to stop them using another method call from my JSP.IS it possible.
How can i do this..
Threads are started succesfully but when i want to stop them JSP throws exception which does not give any meaningfull information..says some internal exception has happened.. I am using tomcat 4.1.18...i am using thread.destroy() method to destroy the threads..
any help will be appriciated..
regards
Akhil Nagpal

HI,
Thanks for your response. Actually threads are started by a bean method which is called from a JSP. Iam using tomcat web container. These threads start listening to some messages which involved JMS. The method is called when I click on start button. Now i want to stop them listening when i call the stop button.
any idea how this can be done..
Akhil

Similar Messages

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

  • Stopping a Thread in Infinite Loop

    I've read several articles on how to stop Threads, and all of them point to using Thread.interrupt(). The problem right now is what happens when the thread is in an infinite loop. For example:
    class A implements Runnable
        public void run()
            while(!Thread.currentThread().isInterrupted())
                  while(true);
    //in other class's main method:
    Thread a = new Thread(new A());
    a.start();
    a.interrupt();The a.interrupt() call only sets the isInterrupted flag in Thread, but it does not terminate the thread as a.stop() would. However, stop() throws a ThreadDeath exception that I would not want to have to deal with. Is there any way to stop this infinite loop thread safely?
    Thanks in advance!

    No need to get snitty. You certainly did not make clear that you are not a newbie at programming. Plenty of newbies who barely have a grasp of the language fundamentals post thread questions here. I thought I did address the question at hand. It seems I misunderstood what you were asking.
    The only way to safely stop that inner loop is like so: while (...) {
       while (!done) {
    }where done is volatile, or all access to it is sychronized on the same lock (meaning you'd sync the !done check above as well).
    If you can't do that, and it's stuck at while (true) and you can't modify the body of the inner loop to check done, then you're SOL.
    (I suppose it's conceivable that 1.6 or 6.0 or whatever it's called will introduce some new safe way to stop that thread, but I haven't heard anything about it.)

  • How to stop a thread in java 1.5 on windows

    Hi All,
    I am using Java 1.5 on windows plateform. I want to stop all the threads which belongs to a particular process when the timeout occurs. In java 1.5 stop() method is depricated and interrupt method just sets the flag and does not stop the thread actually.
    Is there any way to destroy the thread permenently. I am using TheadPool Executor class.
    Regards
    Rinku Garg

    Hi,
    I am having a timer task which is scheduled to run after some fixed time interval when the process started.
    Now this timer task when started, should destroy the active threads of the request. When the request is timed out then the thread is action should termininate.
    In my case run method of particular thread had already made a call to Database through DAO when the time out occurs. So how can I set up a loop in run method which I found on google.
    thread.stop() is deprecated.
    thread.destroy() is deprecated.
    I used thread.interrupt() but it does not stops the thread.
    Please help me in this scenario.
    Regards
    Rinku Garg

  • Stopping a Thread Correctly

    Instead of using myThread.stop()
    I should do somthing like this ... correct?
    //In my Thread Dispatcher Class
    private boolean shouldStop = false;
    private Thread myThread;
    public static void setStopThread(boolean b){
    shouldStop = b;
    public boolean stopThread(){
      return shouldStop;
    public void nullifyThread(){
    myThread = null;
    //In my Thread Class
    public void run(){
    while(!myThreadDispatcherInstance.stopThread()){
      //do some Thread Work
    }//end while
    }//end run method
    myThreadDispatcherInstance.nullifyThread();Will the above code handle everything (aside for the setup and initialization part) to override the depreciation of the Thread.stop() method? Or am I missing somthing?
    oh yea also anywhere I'd need to stop the thread i'd put
    ThreadDispatcherClass.setStopThread(true);

    Looks about right, except that you need to declare setStopThead and stopThread synchronized, in order to force writing to and reading from main memory.
    NullifyThread is almost certainly pointless and unneeded.
    stopThread is a rather poor name. It sounds like it's taking an action, rather than returning a value. shouldStop() or idDone() or something would be better.
    Finally regarding "In my Thread class": Rather than extending Thread, you should implement Runnable. You're not really specializing a Thread's behavior, you're just implementing a unit of work for a thread to run.

  • Stopping a thread from running

    Hai
         I am new to java. It would be helpful for me if someone helps me out in doing this.
         Actually in my program ,I should
    i. Find out whether a particular file exists in the given directory or not.
    ii. If the file doesn't exist, my program should wait for certain timeframe and check for the same file again.
    iii. If the program cannot find the required file within the timeout specified, my application should exit.
         I have done (i) and (ii) using threads. But in the case of (iii), I came to know that stop() method is depricated.
         I am providing my code for a better understanding. Could you please let me know, what would be the best way to stop the thread from running after the timeout is reached in my program?
    Thanx in advance
    import java.io.File;
    public class Fileexists implements Runnable
    static Thread t;
    public static void main(String[] args)
         System.out.println("creation of object");     
         FileExists test = new FileExists();
         t = new Thread(test);
         t.start();
    // run method
    public void run()
         File f = new File("searchfile.txt");
         boolean b = f.exists();
    System.out.println();
    if(b == false)
    System.out.println("Required file doesnot exists");
    try
         t.sleep(20000);
    catch (InterruptedException e)
         // TODO Auto-generated catch block
         e.printStackTrace();
              t.run();
    else
    System.out.println("Required file found");
    } // end of run()
    } // end of FileExists class

    Actually your use of threads is a difference which makes no difference. The JVM starts an initial thread and runs your main(), at the end of which you start a thread and return. So you've just replaced one thread with another. There's no parallel processing.
    The t.run() at the end of your run() method won't work. A particular Thread object can only run once. It will give you an IllegalStateException.
    I can't see how multi-threading will help you with this task at all, all you need is a simple loop with a Thread.sleep in it.
    If you really want to use a separate thread or Timer to implement a timeout (as an exercise) then use Thread.interrupt() to wind up a thread. The looping thread should test with Thread.interrupted() in it's loop condition, if it's in sleep() when interrupted an InterruptedException will be thrown which you should catch and allow to break the loop and let the thread terminate.
    So your loop structure looks like:
    try {
    while(!Thread.interrupted()) {
        ...  do your test
        Thread.sleep(.....);
      System.out.println("Thread terminated by detecting interrupted");
      } catch(InterruptedException ex)  {
         System.out.println("Thread interrupted from sleep");
    You can get the Thread for the main thread simply by storing Thread.currentThread() in a Thread reference.
    I'd suggest using a java.util.Timer to launch your time-out and leave the loop on the main thread started by the JVM.

  • Stopping a Thread (where I don't have control of run)

    Is there any way to stop a thread whose run method simply calls a method of another class?
    For example:
    public class myThread extends Thread
      private String className = ...;
      public void run()
        // get className's "main" method and run it

    Actually...Smarsh is right. This is the correct way
    to stop a thead....stop() is deprecated because it can
    cause a deadlock condition. So, in run(), if you
    defined a boolean like "bStopThread" run would look
    like this:
    public void run()  {
    if(bStopThread)
    return;
    // if we drop here...this is the rest of our run
    un code
    Yeah, I get that's how you should stop a thread...
    Let me rephrase the question a little. Say the thread's run method looks similar to this:
    public void run()
      if (stopped)
        return;
      someOtherClass.aMethod();
    }Once it's in aMethod, I have to let it run until it's done, right? There's no other way to stop a thread other than checking a stop condition?

  • Stopping a Thread (no control on run method)

    Hi,
    How can we stop a Thread like in the following scenario. If we are in the aMethod() and the stopped variable is set to true by some other thread now how can we return from this run method and stop executing the aMethod(). Any tips are helpful.
    public void run()
    if (stopped)
    return;
    someOtherClass.aMethod();
    Thanks

    I miss the scenario here, where a thread is blocked inside a call to some operating system resource (such as accept() or read() or write()).
    In this case an InterruptedException travels like pacman up the stack, until it's caught, and I think that it should be a scenario in all cases, because it can apply to the blocking call (where it applies already), the predictable loop (try { while() { } } catch (InterruptedException ie) { }), and the one-off algorithm, even though in the latter case, if it's extremely important that we know exactly what we were doing when we were interrupted, it's difficult to avoid either a) many try-catch-blocks, or b) a very good way of examining the stack at the moment of interruption.
    This is, in fact, so important, that I would like to urge Sun to change the API for java.lang.Runnable into
    public interface Runnable {
      public abstract void run() throws InterruptedException;
    }Because, in this way, any thread will always have an endpoint. If you choose to rethrow the exception you still mess up the JVM, of course, like it was, causing it to exit. But at least you must provide yourself with the opportunity to let threads not end, or always die softly.

  • Stopping a Thread when downloading

    Hi everyone!
    I'm develop a app to connect to a FTP Server and dowload and upload files. When I click on Cancel button, the app will still running but the download will stop.
    So, my problem is: How can I stop a Thread when i'm donwloading a file?
    I'm using Commons Net 3.0.1 to connect from a FTP. I have tried logout(), disconnect(), abort()... Into Threads I have tried interrupt(), yield(), stop(), destroy()... But not works!
    The "safe way to stop a Thread" don't work for me, becouse I'm not using a While but yes this line code to download the file:
    ftp.retrieveFile(TARGET, SOURCE);
    When I click on cancel button the donwload still running in background.
    PS: Sorry for my english :)

    Problem solved! Using the method retrieveFileStream() and the famous "the safe way to stop a Thread" I can stop it without need to close my app!
    The code was (adapted):
    OutputStream os;
    InputStream is;
    localDownload = new FileOutputStream(new File(LOCAL, NOME_ARQUIVO));
    os = localDownload;
    is = ftp.retrieveFileStream(LOCAL_FTP+NOME_ARQUIVO_FTP);
    if(is != null){
         int bytesRead = -1;
         final byte[] buffer = new byte[4096];
         while ((bytesRead = is.read(buffer)) != -1){
              if(cancelado == false)
                   os.write(buffer, 0, bytesRead);
              else
                   cancelado = false;
    is.close();
    ftp.completePendingCommand();PS: The method completePendingCommand() is fundamental for the download can be stoped.
    Again: sorry for my english :)
    Edited by: 866587 on 17/06/2011 09:53

  • Stopping a thread from "cancel" button

    Hello all,
    I have a problem trying to stop a thread. I have a class that hits database and retrieves lots of data. This retrieval can take a long time if lots of data, so I have a progress bar displayed. This progress bar has a cancel button. I am not sure how to link the cancel button to the thread so the thread can exit. See code below for example of whats going on:
    public class MainApp {
      public void doWork() {
        ProgressBar pbar = new ProgressBar();
        pbar.show();
        DatabaseThread dbThread = new DatabaseThread();
        dbThread.run();
    public class ProgressBar {
      // displays a progress bar with cancel button
    public class DatabaseThread extends Thread {
      public void run() {
        // hit database
    }So how am I to cancel the DatabaseThread class from the ProgressBar class. Thanks for all suggestions!

    what i said is that you need to hava a reference to your thread ine the class that handle the progressBar.
    and in your Thread class you create a method like setCanceled(boolean b)...
    public MyThread extends Thread{
       private boolean canceled = false;
       public void setCanceled(boolean b){
          canceled = b;
       public void run(){
          while(!canceled){
            //do your stuff

  • Problems stopping a Thread

    HI all
    I'm %$&�* with this problem!!! I'm 3 hours trying to solve it!
    I have a BufferedReader associated with a socket this way
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));So I read from the socket this way:
    String result = in.readLine();The problem is that the Thread that reads from the socket keeps stuck at the line String result = in.readLine(); because it waits for
    the stream to provide content.
    I need to stop this thread! so I read the reference and found a method called shutdownInput(); from Socket class. But its not working! when I trigger shutdownInput() it is not releasing my thread to end!
    what do I do?
    thank you all

    You have several options.
    You could use setSoTimeout to specify how long to block. When the block is finished you could check a semaphore variable to sse if you should quit or retry.
    You could call close directly on the Socket.
    You should explore the first option.

  • 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 a thread forcefully. do reply urgent

    i would like to stop the thread . i have used stop() method and also i have tested by giving the threadname = null. but these two not worked . how to stop thread forcefully. urgent.
    with regards

    There is no direct way to stop the thread forcefully. If you have implemented the thread, modify the code so as to break on some flag.
    i.e.
    public void run()
    while (keepRunning)
    ...do some stuff here
    and provide some way to set the boolean keepRunning as false. The loop will exit and the thread will also be destroyed.

  • How to stop a thread without the deprecated Thread.stop() method?

    Hi,
    I am writting a server application that launches threads, but the run() implementation of these threads are not written by me (i.e. i have no control over them): they are third-party programs. That's why i could not use the well known Java tutorial way to stop a thread (i.e. with a global variable that indicates the thread state).
    I would like my server to be able to stop these threads at any time, but without using the deprecated Thread.stop() method.
    Any ideas ?
    Thanks in advance,
    Fabien

    Thanks Pandava!
    I was arrived at the same conclusion... As to me, it is a very bad issue, because it means for example that a servlet server can not stop any servlet it launches (especially for preventing infinite loops).
    If i want to be strictly JDK 1.4 compliant, i should not use Thread.stop(). But if i don't use it, i don't have any ideas of how stop a thread that i don't control...

  • Stopping a Thread.... again

    Hi all,
    a couple of months ago I've posted a similar topic, on how to stop a thread without using the deprecated stop() method. Still, no result. I have a great deal of calculations that should be done in a separate thread. Due to the fact that the calculations might take up to 10 secons (or more), I would like to give the ability to the user to stop the process of calculations.
    public class Calculations(){
        //Field Declaration
          Thread t;
        public void doTheJob(){
            if(t != null)
                 t = null;
            t  = new Thread( new Runnable(){ public void run(){
                <PERFORM THE CALCULATIONS>
            t.start();
        public void stopTheJob(){
                 <HOW????, t.stop() works "fine">
    }The stop() method of class Thread will do perfectly and stop the procedure. However is deprecated. I've checked the alternative of stop using while( t!= null) loops, but there is no loop in the procedure!! There is just a bunch of operations that should be done in a separate thread. It is logical that something as the following won't do if the procedure has already started.
        public void stopTheJob(){
                 if( t != null)
                      t = null; //No point if the procedure has already started
        }Please correct me if I'm wrong, but help me understand how...
    I am not a programmer and not that smart but I still want to solve this issue.
    I would gladly provide more information if necessary.
    Thnx in advance,
    F.

    There are fundamental problems with monitors (i.e. synchronized bits). You can be sure they've given a lot of thought to cleaning up and decided there's no safe way to do it.
    stop still works and there are very rare situations in which I'd use it. In particular if the thread were running someone else's not fully trusted code and a framework decided an infinite loop was happening. Depracation is a warning, not an error.
    However it's generally no problem at all to have a thread watch for being interrupted and stop itself.
    Generally the interrupt call is the best mechanism since it kicks the thread out of wait or sleep, or sets a flag which you can test (or which will cause an exception next time you wait or sleep.

Maybe you are looking for

  • Lookup in BPM

    Hi I have a message A which is passing through BPM and is splitting into 2 messages B and C (using 2 differnt message mappings). Now is it possible to send B first and then wait for 30 secs and do a look up from A to check a value in the target side

  • Pen Pressure not working in Photoshop CS5.1

    Hello, I've looked at a lot of questions and answers concerning pen pressure in this forum, and I've tried a lot of things to fix this problem. I have a Genius MousePen 6x8 and use Photoshop CS5.1. It's been a while since I used my tablet, but it use

  • Style sheet changing when applied to text within a table

    Hi everyone, I'm using ID CS2. I've defined a paragraph style sheet with the regular weight of a certain typeface, however when I apply this style to text within a table, the typeface changes to the bold version of the font even though the regular ve

  • Sent messages disappeared when I rebuild mailbox

    15 minutes ago, my SENT email box in MAIL contained sent messages from May 11, 2011 to date, but searches run on that box only would pull up emails from early December. I rebuilt the mailbox and now only sent emails from early December to-date appear

  • Error installing LabVIEW 2011 on Win 7

    I'm getting an error installing LabVIEW 2011 Professional: I found a thread concerning missing MSIs, which suggested that one run setup.exe with the /log function, so I did, but I don't think it actually says anything useful. I also found a Microsoft