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();
     

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++)

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

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

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

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

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

  • Kill and System.exit

    Is there a way (with Linux) to issue the kill command on your java process so that System.exit(0) is called and you know that your shutDownHooks will run?

    Thanx again for the reply, Freddy
    first things first:
    System.exit(0) does not work in this case..
    and the code is reached..
    // main class
    public class AdminApp {
    public AdminApp() {
    public static void main(String[] args) {
    AdminApp adminApp1 = new AdminApp();
    AdminFrame frame = new AdminFrame();
    /// admin frame class
    public class AdminFrame extends JFrame{
    public AdminFrame() {
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    this.pack();
    this.setSize(600,480);
    this.setVisible(true);
    groupsMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    desktop.add(new AdminGroups());
    //admingroups class
    public class AdminGroups extends JInternalFrame {
    private JTextArea textArea = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane();
    JPanel groupPanel = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    public AdminGroups() {
    setSize(200,300);
    setTitle("Edit Text");
    setMaximizable(true);
    setIconifiable(true);
    setClosable(true);
    setResizable(true);
    scrollPane.getViewport().add(textArea);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(scrollPane,BorderLayout.CENTER);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    getContentPane().add(groupPanel);
    private void jbInit() throws Exception {
    groupPanel.setLayout(xYLayout1);
    }

  • Thread: Process exit code 1073741819

    I am using JDeveloper 10.1.3 and specifically JSF technology to build a web application. Lately some pages stopped working or displaying with the command line of JDeveloper displaying the following error: "Process exit code 1073741819". Where can I find a reference for such codes and their meanings? I also need to know the meaning of this error and how it can be solved.
    Thank you in advance for your help

    Hi,
    I have encountered a similar issue in one of my SSIS packages. The package performed the following tasks.
    Check for the PSV files in the source directory. These files are of two types *phone*.psv format and *lead*.psv
      Convert the new files into .xlsx files and then log the processed file names into another table
     The file processing for the two types of files was being done in two different For Each Containers, which processed the files parallel'y if both the type of files were found.
    The package ran fine when only one of the file types were found, but if both the types of files were found then the package failed with the same error. 
    "The return value was unknown.  The process exit code was -1073741819.  The step failed."
    On checking up the details provided on this thread i found the culprit was the parallel file processing causing a conflict in the cache usage, thereby causing this error. (Refer
    http://support.microsoft.com/kb/924016?wa=wsignin1.0 )
    I then changed the package execution process in a manner that the two for each containers executed one after other even if both the types (phone, lead) of files were found. I basically made the control flow sequential from parallel. 
    The issue didn't reoccur a single time after that.
    So the point here is to try and make the file processing tasks as serial (in CONTROL FLOW) as possible in the sequence of execution, thereby bypassing any instance where the two different operations doing similar job (thereby using the same cache) do not
    create a conflict in package execution.
    Hope this helps to clear the Air on this issue to some extent.
    Thanks
    Suvrat

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

  • GWIA 702HP1a unable to unload and restart

    Hi,
    i have found a problem by the GWIA version 702HP1a running on Netware 6.5
    SP6.
    The GWIA has open send threads and in the SEND folder store many mails, then
    i can not restart (F6) or unload (F7). The GWIA freeze - i must restart the
    server.
    If the folder is empty and no Ssnd threads are open, then unload and restart
    the GWIA successful.
    I have as workaround protect the GWIA. But the problem is the same - F6 and
    F7 is not working.
    Then i find out more Iissues by "unload address space = GWIA":
    - on Netware 6.5 SP6 unload the GWIA. <-OK
    - on Netware 6.5 SP5 need a kill address space.
    These problems are on standalone servers and netware cluster nodes. I can
    reproduce that in 5 different enviroments.
    Regards,
    Joerg Buelow

    I've also had two issues with the GWIA hotpatch and have left the GWIA "unloading" for 20-30 minutes and it will not unload. Is
    Is it possible that this is a symptom of a known issue with the original HP2 release, because at the same time, it creates the huge files in the GWIA\000.PRC\GWWORK folder...
    Stormy
    >>> LCIS<[email protected]> 6/21/2007 5:52 AM >>>
    "Joerg Buelow" <[email protected]> wrote in
    news:t8uei.355$[email protected]:
    > Hi,
    >
    > i have found a problem by the GWIA version 702HP1a running on Netware
    > 6.5 SP6.
    >
    > The GWIA has open send threads and in the SEND folder store many
    > mails, then i can not restart (F6) or unload (F7). The GWIA freeze - i
    > must restart the server.
    >
    > If the folder is empty and no Ssnd threads are open, then unload and
    > restart the GWIA successful.
    >
    > I have as workaround protect the GWIA. But the problem is the same -
    > F6 and F7 is not working.
    >
    > Then i find out more Iissues by "unload address space = GWIA":
    > - on Netware 6.5 SP6 unload the GWIA. <-OK
    > - on Netware 6.5 SP5 need a kill address space.
    >
    > These problems are on standalone servers and netware cluster nodes. I
    > can reproduce that in 5 different enviroments.
    >
    >
    > Regards,
    >
    > Joerg Buelow
    >
    >
    >
    Its not frozen. Its finishing the threads it started. If you are like me,
    when you go to shutdown, some bozo just send a 22 meg email to 15 people
    on different email servers. and 3 of thoes are really slow. If this is in
    fact what you have going on, then try the /killthreads switch. In
    ConsoleOne its under SMTP/MIME > Settings > Kill Threads on Exit or
    Restart. Of course, it might be possible to loose email that way, but
    when you tell gwia to exit, it exits!

  • Kill a thread and remove the element from the vector

    Hi All
    I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
    Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
    However, I want to delete this element from the Vector now.
    Can someone please throw some light on this?
    Here the code I have written for this:
    try
         System.out.println(counter);
         int xCoord = generator.irand(25,200);     // X-coord of AP
         int yCoord = generator.irand(25,200);     // Y coord of AP
         listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
         listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
         for(int i=0;i<vnuBS.returnBSList().size();i++)
              if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
                   double c = exponential() * 10000;
                   long timeToService = (long)c;
                   System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
                   vnuBS.returnBSList().get(i).reduceChannelCounter();
                   System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
                   mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
                   mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
                   mobileNodesThread.elementAt(mobileNodeCounter).start();
                   mobileNodesThread.elementAt(mobileNodeCounter).join(100);
    //                              System.out.println("Died");// thread dies after join(t) milliseconds.
                   System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
              else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
                   listMN.remove(this.listMN.lastElement());                         //dropcall
                   System.out.println("Removed "+mnId);
                   removeCounter++;
                   mnId = mnId--;
                   mobileNodeCounter--;
              mnId = mnId+1;
         Thanks a lot.

    I'm not sure if what you are trying to accomplish is correctly implemented.
    The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
    Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
    I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish?

Maybe you are looking for

  • Copying data to CD

    I am simply trying to back up my data by copying it onto some High Speed CD-RW. I had purchased a box of them and have used each one of them once. No matter what I do I can't seem to figure out how to reuse the CD, even if the first copy to a specifi

  • Mac Mini Late 2012

    Can anyone confirm whether the latest Mini, Late 2012, can run Lion?

  • Unable to check the "calendars" checkbox in isync

    I want to Sync my calendars with my razr phone, but when i try to check the calendars checkbox, a dialog box pops up telling me i need to start ical, I click the open ical button, ical opens, but the checkbox still does not check. I click the box aga

  • Cost Center Allocation - PCA

    Experts, If a Cost Center allocation is done, would it also affect the Profit Center's associated with it also ? All answers would be duly appreciated and rewarded with points. Thanks, Nandita

  • View Stack in a FlowBox

    Hello, I have a application with one Grid that is displayed when the application starts. With a additional button I add 2 other Grids. This works with a ViewStack around the 2 optional Grids. The 3 Grids are horizontal. Now when I minimize the applic