Kill thread

i have a java process that will perform some tasks and creates a thread to do time-intensitive tasks. this process will be excecuted several times a day ( may every 2 or 3 min ). by end of the day i may have some 300 or 400 threads created.
now i want to kill the thread at the end of each process. this is my code
ResubmitThread resubmitThread = new ResubmitThread();
resubmitThread.start();
resubmitThread=null; // to kill the thread
private class ResubmitThread extends Thread {
void run() {
boolean shouldRun=true;
while(shouldRun) {
..... do some stuff. this takes around 10 minutes to complete
shouldRun=false;
============
mu question is whether resubmitThread=null; will make my thread ready to be garbage collected ? is there any way of 'killing' a thread ?
thanks

thank you so much.
is it any different from my code written above
where i am making shouldRun as false ?
essentially when the run method is completed , the thread is stopped/killed ? i know it is not killed/garbage collected immediately ,
but we don't have to worry any thing in the code. am i correct ?

Similar Messages

  • How to kill threads in obiee server

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

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

  • JPDA Examples TTY kill thread.

    Hi all:
    I've try to run the example com.sun.tools.example.debug.tty.TTY it works pretty well but I dont understand exactly how to use the command kill:
    kill <thread> <expr> -- kill a thread with the given exception object
    <expr>: a Java(tm) Programming Language expression.
    I dont understand exactly what they mean with the <expr> I've try kill 5 new java.lang.String("Killed") or kill 5 new java.lang.Throwable("Killed")
    Did someone here knows how to use JPDA to kill a thread?
    Can you give me an syntax example for that command?
    Thanks for any help.

    I've found a similar post at
    http://forum.java.sun.com/thread.jsp?forum=47&thread=274201
    timbell tells to use the following syntax:
    kill 0x129 new java.lang.Exception()
    but in my case I've try
    Reference Handler[1] suspend 29
    Reference Handler[1] kill 29 new java.lang.Exception()
    killing thread: 142.120.93.217_170_Receive
    Reference Handler[1] Thread not suspended
    Expression must evaluate to an object
    And it does'nt seems to work.
    Any helps will be appreciate.
    Thanks

  • Killing thread

    hi
    all
    i am trying to stop thread by callling stop() method on Thread object
    but it is deprecated it is saying. can u tell me what is the method in 1.4 for killing a thread
    class ThreadDemo
    public static void main (String [] args)
    MyThread mt = new MyThread ();
    System.out.println("thread alive or not ? :: "+mt.isAlive());
    mt.start ();
    System.out.println("thread alive ? :: "+mt.isAlive());
    for (int i = 0; i < 50; i++)
    System.out.println ("i = " + i + ", i * i = " + i * i);
    mt.stop();
    System.out.println("thread Died or not ? :: "+mt.isAlive());
    class MyThread extends Thread
    public void run ()
    for (int count = 1, row = 1; row < 20; row++, count++)
    for (int i = 0; i < count; i++)
    System.out.print ('*');
    System.out.print ('\n');
    }

    Methods like stop, suspend etc. are deprecated because it was realised there was no really safe way a Thread could be halted from outside itself without risking subtle problems of timing, partially complete updates and so on.
    These days you have to be more polite and ask a thread to stop rather than halt it. This is generally done by setting some kind of tlag which a thread that loops tests each time arround the loop. Often the best approach will be to use interrupt. Generally Interrupt simply sets a flag which the thread can test using Thread.currentThread().isInterrupted(), but it also "wakes" a thread that might be waiting or sleeping, causeing these methods to exit with an InterruptedException.
    So, in your example you'd put:
    for(int row = 1; row < 20 && Thread.currentThread().isInterrupted(); row++)

  • Need some help killing threads (not in the way already mentioned..)

    I have read the ways in which we should safely kill a thread - and for the most part i understand that. But my question is HOW to implement it in the way that I need.
    Basically I have a multithreaded (ewww) app that really is a large job scheduler running 24/7. It can run anywhere from 1 to 15 jobs at a given time. This is fine. What i need is to have the ability to 'kill' a job when I need to. When the app daemon decides its time to run a certain job (based on business logic) it kicks one off, which is a class I made that implements Runnable.
    public class SchedulerProcessThread extends SOQBase implements Runnable{}
    when its time to start a job i do the usual:
    SchedulerProcessThread spt = new SchedulerProcessThread(blah);
    Thread t = new Thread(spt, "fooname");
    t.start();
    Now, this comes to my problem of where/how to kill the job (if needed). A SchedulerProcessThread is linear and finite so it will always have a termination point - it never loops. And when one is kicked off - i do not have a reference to it anymore - I mean, I couldnt if i am constantly running new jobs, potentially hundreds every hour. And jobs can be started in various places in the app, depending upon whether others are already running, etc.
    I wish to implement the do-while (alive) logic on the job thread. So in the 'run()' method of my SPT class, I would like the:
    while (alive) {
    doProcessing();
    But how can i invoke a method on my class [SPT] so that it changes the alive var from true to false when i do not have a reference to it?
    As a side note, I have a command prompt on the app whereby i can call up all the running 'jobs' which is a list of the running threads under a threadgroup called 'soqjob' (all new Threads that are started with a passing param of and SPT object are under the 'soqjob' threadgroup). So now i can see all those 'soqjob' threads which are currently running Thread objects that have been passed new instances of an SPT class.
    Is there anyway i can grab the 'soqjob' thread of my choice and somehow access my SPT class that was originally passed to it in the Thread constructor? if so, then I could pass in the command to stop the do-while loop.
    Hmm - does any of this make sense? If i can sum up, the problem is i do not know how to access my own SPT class once I have passed it into a thread object and invoked that thread object's 'start()' method. if i can do that, then i can switch the ALIVE var from true to false and thereby kill the SPT job i need.
    Any ideas?
    Many thanks
    Ian

    I would add a Collection (synchronized) to the Scheduler that holds a reference to all the Processes. Pass a reference of the Scheduler to the Processes so that when a Process is done, it can remove itself from the Collection.
    public class Scheduler {
         private Collection threads;
         public void addProcess() {
              Runnable runnable = new ProcessThread(this);
              Thread thread = new Thread(runnable);
              thread.start();
              threads.add(thread);
         public void removeProcess(ProcessThread thread) {
              threads.remove(thread);
         private Thread getSelectedThread(Component c) {
              //Find Thread in Collection and return it
         private class Action implements ActionListener {
              public void actionPerformed(ActionEvent e) {
                   Thread thread = getSelectedThread(e.getSource());
                   thread.interrupt();
    class ProcessThread extends ... implements Runnable {
         private Scheduler scheduler;
         public ProcessThread(Scheduler s) {
              this.scheduler = s;
         public void run() {
              while (!Thread.interrupted()) {
                   try {
                        doProcessing();
                        Thread.yield();     //Give the other Threads a chance to do some work
                   } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
              this.scheduler.removeProcess(this);     //Remove this Thread from the Scheduler's Collection
    }Did you consider using the classes java.util.Timer and java.util.TimerTask?

  • Killing Threads

    Hello all,
    I'm using oracle chart builder for presenting data in my
    application. I use it after supplying its data for gif file
    generation. The chart is stacked bar but I don't think this is the
    problem.
    The problem is that it generates the gif file successfully but my
    application is still running after the main method is finished, I
    debugged it and I found about three threads are up:
    Thread[AWT-EventQueue-0]
    Thread[SunToolkit.PostEventQueue-0]
    Thread[AWT-Windows]
    I doubted my code - but I'm taking it copy paste from developer's
    guide - and I debugged another Java file from a sample that comes with
    the kit and the same problem happened ?!?!?
    Does anyone know y?
    I saw lots of SunToolkit.PostEventQueue-0 problems here in google
    groups, but I don't find matching my situation.
    I used in testing both Oracle JDeveloper 9i release 3, and IBM
    WebSphere Studio Application Developer 4.0.3
    Thankx

    That will not work because these are threads started by the event handlers and gui objects not by processes he wrote. I honestly do not know that it is possible to kill these threads. I know you could have used something like the stop process in the past but not any longer. System.exit is really the only way I have seen to do things like that. I would say that maybe the best sollution you could hop for is to keep the window active even when the user closes it so then when they later ask for it again you can return the same window and keep it to those three threads being the only extra ones you have running.

  • How to kill thread

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

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

  • Killing thread after timeout (j2se 5)

    Hi. thread.stop and thread.destroy() is deprecated. The javadoc for thread.stop() recommends the thread to check a flag to see if it should commit suicide. My problem is that the thread uses an method which locks making the thread unable to check if it should die (code below). How can I externally kill that thread?
    Thread t = new Thread(){
    public void run(){
    Spring s = new Spring();
    Tools.p(Tools.DEBUG, "Returverdi fra spring-algoritme: %s", s.compute(g, gu));
    t.start();
    t.join(10000);
    if (t.isAlive) t.stop() //but stop is deprecated... alternatives?
    Sincerely
    Fredrik 

    Let me restate the question to be sure I understand:
    You want to launch a possibly long duration process and let it run for a specified time. If it's still running, you want to kill it. If that's the case, something like this:
    public void run() {
       try {  doLongProcess(); }
       catch ( InterruptedException e ) {  }
    }Externally, interrupt the thread when time is up.

  • Killing thread after JOptionPane

    I have a class that is not a GUI object but it calls a JOptionPane to display a message popup... I do not provide a parent to this JOptionPane. Im writing a unit test for this class and notice that after my last statement there are still living threads. I am guessing the gui thread. Is there a way to kill the GUI thread associated with the JOptionPane after it is displayed. Or do I have to do a system.exit at the end of the application that will end up using this class ????

    Let me restate the question to be sure I understand:
    You want to launch a possibly long duration process and let it run for a specified time. If it's still running, you want to kill it. If that's the case, something like this:
    public void run() {
       try {  doLongProcess(); }
       catch ( InterruptedException e ) {  }
    }Externally, interrupt the thread when time is up.

  • Properly closing socket and killing thread in cmd window

    Hey all,
    I'm creating my socket connection in a program that i am running in a cmd window. For what i need in my prog, i have a loop that tries to connect every 5 seconds, and even after that, I need to continue looping to check and try to connect.
    The only way i can end the program is to cntrl-c or X out of the program. What i need to know is there a way to properly clean up the thread and close the socket w/o any memory leak issues?
    Thanks

    What i need to know is there a
    way to properly clean up the thread and close the
    socket w/o any memory leak issues?All modern popular use OSes clean sockets, threads and memory (normal) when the application exits for any reason at all.

  • Killing threads on exit

    hello,
    I'm writing a program that reads in a couple of files which are created by another program.
    Sometimes only 1 file will be read, sometimes there will be two.
    In some cases even none.
    I'm using 2 threads to check if the files exist.
    the thread is terminated when it has found a file (with a boolean value and while statement)
    My problem is that when only 1 file has been found, the thread will continue to run even if my program is terminated.
    Is this supposed to be doing this?
    How can i make sure there is nothing more running when the user exits the program?

    Since you have not posted the code to get better help; I would suggest roughly to set both threads as Daemon before the threads starts. This will allow the JVM to exist
    ex:
    public class Main {
         public static void main(String[] args)throws Exception {
              Runnable run = new MyRunnable();
              Thread t = new Thread(run);
         //     t.setDaemon(true); // this will allow the JVM to exit
              t.start();
              Thread.currentThread().sleep(1000);
         class MyRunnable implements Runnable {
              public void run() {
                   while(true) {
                        try {
                             System.out.println("here-->" + System.currentTimeMillis());
                             Thread.currentThread().sleep(1000);
                        }catch(InterruptedException interEx) {
                             // Restore the interrupted status
                           Thread.currentThread().interrupt();
         

  • Killing Parent thread can kill child thread

    hi frnds
    can u help me on thread
    i want to know if i am kill my parent thread.can it automatically kill chhild thread also.
    and i want to know is there any way in java to kill thread
    plz reply

    ajju29 wrote:
    and i want to know is there any way in java to kill threadNo, not safely and not reliably. Since there's no way to "kill" a thread without its cooperation, the previous question is not relevant as well.
    What you want to do is set some flag that your thread periodically checks and maybe send an signal and/or interrupt to tell the thread to check the flag earlier. The thread should then quit on its own.
    Everything else is unfixably broken.

  • Thread problems - shutting down.

    Okay, I've got my multi-threaded server program working just fine and all is well...until I shut down the server.
    By some quirky twist of fate, java chat servers seem to be a popular education assignment in the last two weeks, which will probably put some people off answering this simply because of all the clueless posts on the subject recently. :)
    Anyway, a little background on how I'm doing things first.
    At the top there is the Server object, which is implementing Runnable. This instances the ClientManager, creates the ServerSocket and then kicks off its own thread and loops in the run() method waiting for connections while a boolean is true. If it gets a connection it calls the ClientManager addConnection() method and passes it the received client socket.
    The ClientManager holds a List of ClientConnections and provides methods to add and remove ClientConnections. The ClientManager also runs in its own thread by implementing the Runnable interface and uses its run() method to loop through checking for incoming messages from each client.
    A ClientConnection object also runs in its own thread via the Runnable interface. This checks for incoming messages from the client and stores the String ready to be received by the ClientManager and broadcast to all ClientConnections.
    So, you've got the Server running in its own thread, the ClientManager running in its own thread and the ClientManager maintaining a List of ClientConnections, each running in its own thread.
    I'm starting my threads like this:-
    // Constructor.
    Public SomeObject() {
        start();
    // Runnable method.
    Public void start() {
        // threadObject is private class variable.
        bThreadActive = true;
        this.threadObject = new Thread(this);
        threadObject.setDaemon(true);
        threadObject.start();
    }I'm running my threadded object like this: -
    Public void run() {
        do {
            // Do work here.
        } while(bThreadActive);
        // Activates the shutdown method for this object.
        shutdownObject();
    }I'm shutting down my threads like this: -
    Public void shutdown() {
        this.bThreadActive = false;
    // The main shutdown code.
    Public void shutdownObject() {
        // Kill thread object.
        this.threadObject = null;
        // Do other stuff.
    }Which I think should work fine. Anything wrong with the above?
    I'm getting problems with NullPointerExceptions with the Server object at the point where it tries to shutdown the ClientManager. This works by shutting down all ClientConnections in the List first and then emptying the List before killing its own thread. Also, the Server object seems to shutdown before the ClientManager. And other such weirdness.
    I know you're all going to ask for specific code and a stacktrace, which I'll provide....I just want to check that my method for using threads as above is correct first, so I can rule that out - mostly because I suspect I'm missing some vital piece of knowledge on using threads....things are not working as I expect.
    Anyway, a quick answer on the above and then I'll start posting more specific info.
    Thanks all :)

    Ooops....my mistake. I was calling shutdown() twice. Once from the GUI code and automatically from after the loop in the run() method. Funny how the stacktrace doesn't drill down any further than the method that makes this call.
    Okay, its almost all working perfectly, except for this part....
        //  Start accepting client connections from the server service.
        public void run() {
             while(bThreadActive) {
                 if (sockServer != null) {
                     if (!sockServer.isClosed()) {
                         try {
                             sockClient = sockServer.accept();
                             if (sockClient != null) {
                                 this.clientManager.addClientConnection(sockClient);
                                 this.pOutput.printOutput("Connection accepted from: " + sockClient.getInetAddress().getHostAddress());
                         } catch (IOException ioe) {
                             if (bThreadActive) {
                                 this.pOutput.printOutput("ERROR: Could not accept incoming client connection");
                         } catch (NullPointerException npe) {
                             // Leave this for now.
             shutdown();
        // Shutdown the server service and disconnect all client connections.
        public void shutdown() {
            try {
                clientManager.stopThread();
                sockServer.close();
                threadServer = null;
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            } catch (IOException ioe) {
                pOutput.printOutput("ERROR: Could not cleanly shutdown the server socket");
            pOutput.printOutput("Server service shut down successfully");
        // Stop the server thread (automatically shuts down).
        public synchronized void stopThread() {
            bThreadActive = false;
        }When I call the above like this from the GUI object...
        // Stop the server.
        private void stopServer() {
             try {
                  server.stopThread();
                  setGUIMode(MODE_DISCONNECTED);
             } catch (NullPointerException npe) {
                  npe.printStackTrace();
        }...the string "Server service shut down successfully" from the completion of the shutdown() method never appears, so it looks as though its not executing.
    But if I do this instead in the stopServer() method and remove the shutdown() call in the run() method, it works......but I get two (sometimes three) outputs of "Server service shut down successfully" which makes me think its being run twice somehow.....once before the ClientManager has been shutdown and once after or twice after.
    Server service shut down successfully
    Shutting down Client Manager...
    All client connections disconnected
    Client Manager successfully shutdown
    Server service shut down successfully
    Server service shut down successfully
    Any ideas?

  • PROBLEMS WITH A THREAD!!!

    Hi, guys!
    Posted this in another forum, but no good answers...
    I got a class "GUI" which is calling a method in class FileCopy on a button-click.
    Class GUI calls -------> copy in class FileCopy
    The FileCopy-class looks kinda like this:
    public class FileCopy implements Runnable {
    Thread thread = null;
    public void copy( ...params...) {
    thread = new Thread(this);
    // Asign some vars
    thread.start();
    private void copyFiles(File file, File destination) {
    // Copy the file
    public void run() {
    for (Iteration e = collection.iterator(); e.hasNext();)
    copyFile((File) e.next(), destination);
    // Kill thread next
    The problem is that the thread seems to call the metod copyFiles and then (before the copyFiles-method is done) go to the part in run where I kill the thread. That results in a non-copied file!!!!
    I've tried to use the join-method to get the thread to wait for the copyFiles-method to complete, but then the GUI freezes and that's not an option!!!
    Plz help!!!
    /Andrew

    Hi
    you are already in the event thread (dispatching thread)
    and you don't need to spawn another thread, just handle the event normally
    in your event handler.
    if you really want to use thread use a Timer to copy (set a low interval)
    or
    class FileCopy implements Runnable {
    FileCopy(params...) {
    // Set your file names and params here
    private void copyFiles(File file, File destination) {
    // Copy the file
    public void run() {
    for (Iteration e = collection.iterator(); e.hasNext();) {
    copyFile((File) e.next(), destination);
    // let the thread end normally
    // event handler
    public void actionPerformed(ActionEvent e) {
    Filecopy copy = new FileCopy(params...);
    new Thread(copy).start();
    I hope this helps

  • Game main loop using Thread. How to ?

    Hello !
    Is anybody know what happened with threads, which was created by MIDLet when MIDLet will be closed ?
    More details: i design a specific game engine for MIDP2.0. In many available resources main game loop implemented through separate Thread, but one thing is just missed - how to correctly stop this thread when player want to exit from game ? Mostly all examples just call notifyDestroyed() and do nothing more. But I think what it is wrong program behaviour. So I have questions to advanced MIDP programmers:
    1) Do we need correctly stop all Threads before call notifyDestroyed() or can just forget about it ? (I think need to stop all threads ...). Maybe some documentation or usefull link is available about this or related problem ?
    Where get documentation about Threads in Java, and how to VM stop thread during garbage collection. As I think exactly G&#1057; will destroy MEDLet threads if I don't stop it manually ?

    ... But I think that all created threads should be
    killed in logical right place. For example, if thread
    is using for animation and created in Canvas object,
    this thread should be killed before killing Canvas
    object (for example command "Exit" have been choosen,
    firstly we kill thread, secondly we call destroyApp )
    If midlet uses user interface, I never called
    notifyDestroyed() from my own created thread, because
    application usually should be finished when command is
    choosen or some key pressed.I completely agree with both notes, and even think what I was wrong in general - when decide to use main loop paradigm in PC way (strictly speaking I just copy paradigm from PC project). You give me an good idea - use custom-purpose threads instead general-purpose "main-loop" thread. I just will look on this thread from other point of view and use it only for call update() for my canvas and provide way to handle time-depended actions (say for animation). No anything more. So all I will need - proper synchronization when perform time-depended action.
    So I can stop that thread from destroyApp() when AMS want to destroy my MIDlet, and I can stop that thread from any event-handler in my canvas (in command handler or just key-pressing handler) and then call notifyDestroyed() in order to stop MIDLet manually. So no more calling notifyDestroyed() from any MIDlet-own threads. What you think ?
    Just for intresting - citation from JVM Specification:
    2.16.9 Virtual Machine Exit
    A Java Virtual Machine terminates all its activity and exits when one of two things happens:
    * All the threads that are not daemon threads (�2.17) terminate.
    In CLDC specification no any changes in this paragraph was made, so we can say what if we does not stop all threads which we create in MIDlet the MIDLet execution will be endless ? It is intresting - implementation JVM in real device start JVM for each MIDLet or start JVM once and start MIDlets in this one-session JVM ? In first-case it is possible to just stop JVM (with all threads) and release any resources (looks little dirty, but why not ?) in second-case all "zombie" threads can live endless (until device switch off) and just decrease performance and eat resources ...
    Need more specification ...
    Many thanks to RussianDonz for collaboration.

Maybe you are looking for

  • HttpServletResponse.sendRedirect bug in Release 2

    I think I've come across a bug with the HttpServletResponse.sendRedirect() method and OC4J in 9iAS R2. I've constructed the following statement: response.sendRedirect("http://www.myurl.com/index.jsp?src1=http://www.abc.com&src2=http://www.somewhere.c

  • Is there a way to "red eye" more than one photo at a time?

    Is there a way to "red eye" more than one photo at a time?

  • How to use jquery plugin jResponsive, please help!!

    Hello, Can someone show me how to integrate JResponsive plugin into Edge Animate with an example? Here is the link to Jresponsive website: Jresponsive Thank you.

  • After Effects and Premiere Pro, Which do you use first?

    Hi. I use premiere pro to edit my videos and now I am learning about after effects and removing blemishes with AE. My question is, do I edit my audio, colors, etc. in premiere first then do after effects for blemishes or vice versa? I don't want to s

  • WLC5508 problem connect AIR-CAP1602I-R-K9

    Добрый день, Точка Air-cap1602 не может подключиться к контроллеру, В чем может быть проблема? Спасибо. AP885a.92bb.97ab#sh inventory NAME: "AP1600", DESCR: "Cisco Aironet 1600 Series (IEEE 802.11n) Access Point" PID: AIR-CAP1602I-R-K9 , VID: V01, SN