Kill Event thread or abort/restart main VI

I am looking for a method of killing off an event thread once it is in the middle of executing.  A description of my problem is below (I am using labview 8.2).
My main VI is reading my DAQ and constantly updating the main control panel with the data and logging the data at operator defined rates.
The user can then select different functions for the system to execute using an enumeration and a Boolean control.
When the user selects the Boolean control (run button) an event is triggered, the ENUM is read, and various sub-vi's execute to complete the function (none of the sub-vis have visible control panels all of them use some of the data from the main vi's controls/indicators passed by reference).
The user also has a stop button.  If pressed another event is generated.  I would like to kill the run event in this case, at any point in its execution (long delays in some of the sub-vi's).  Then I can set the system back to default and continue on selecting another function in the enumeration and run button press.
I would also considering aborting the main vi and then restarting it as long as the front panel remains open.

I appreciate the reply.  I agree that the event cannot be killed, I have tried several "tricks".  The code does go into the stop event while the run event/sub vi is executing. 
 I had the ref to the stop button wired into the sub-vi's already.  Some of these vi's are fairly in depth, do you have a recommendation to continuously read its state without getting into every loop etc that is in the sub-vi?  I was trying not to monitor this buttons state at every point in the sub-vi's block diagrams.
Thanks

Similar Messages

  • How can I kill a thread.

    I have read the many threads about killing a thread but they dont answer the question I need to know.
    In class#1 I have the following snipet of code:
    for (int i=0; i < docs.size(); i++)
        try {
            boolean blncompleted = false;
         Map object = null;
            OntologyCreatorThread  ontThread = new OntologyCreatorThread ();
         ontThread.start();
         ontThread.join(15000); // Allow thread to process for up to 15 seconds.
         // If thread is still running, kill the thread.  I dont care about
         // clean up since its only using memory and cpu, no DB is ever touched.
         if (ontThread.getState().toString().equals("RUNNABLE")){
             ontThread.interrupt();
                ontThread.stop();
                // set flag to false
             blncompleted = false;
            else {
                // set flag to false and do a ton of other processing.
             blncompleted = false;
             object = ontThread.getObject();
        catch (Exception Ex){
            Ex.printStackTrace();
    In my thread I have the following:
    public class OntologyCreatorThread extends Thread {
        Map object = null;
        public OntologyCreatorThread(){
        public void run() {
           try {
             // The line below takes forever to run sometimes.
             object = functionCallToApi(stringOfText);
        public Map getObject() {
         return objects;
    If the thread takes to long to run I just want to kill it.
    I have tried interupt and stop and both dont work.  Inside the run method of the thread I call an external API
    which I pass a string of text.  I can not get into that code because its from a Off the shelf product that we dont
    have the code to.  If the call in the run method takes to long I want to just kill this thread in the main class(#1). 
    No matter what I do I cant get the damn thing to stop.
    The line below takes forever to run.
             object = functionCallToApi(stringOfText);
    Putting it in a while loop wont solve this problem because the processing is still taking place in the call to the api.
    Thanks in advanceMessage was edited by:
    Storm897

    Couple of things to consider:
    1. Note that Thread.interrupted() and t.isInterrupted() are very different methods. The former clears the interrupted status so that a subsequent call will return false. The latter does not affect the interrupt status on the thread.
    2. If your "atomic step one" catches an Exception, then you might be swallowing an InterruptedException. Basically the rule when a Thread is interrupted is that if it is in a blocking call, an InterruptedException is thrown. Otherwise, isInterrupted is set to true. So if you have blocking (I/O) calls in "atomic step one" and you're catching Exception, then it might be that the InterruptedException goes completely unnoticed.
    3. If "atomic step one" takes a long time and you really want to abort the thread instantly, then you need some kind of method for doing so--you need to program in safe "stopping points". For example:
    public class Helper implements Runnable {
       private boolean _continue = true;
       public void cancel() {
          _continue = false;
       public void run() {
          _continue = true;
          try {
             // Do something until in safe/stable state
             if(!_continue) return;
             // Do something until in safe/stable state
             if(!_continue) return;
             while(_continue) {
                 // process single record in large data set
                 // Safe to stop at the end of each loop
             if(!_continue) return;
             // Do something else . . . etc.
          } catch(InterruptedException ie) {
             _continue = false; // Unnecessary, but here for illustration
    }Casual programmers often don't care whether the thread stops safely or not, but it really is important especially if you are in the middle of some kind of transaction. That's why destroy(), cancel() et al are deprecated.

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

  • JColorChooser hangs event thread on Linux x64

    I am finding that repeatedly displaying a JColorChooser, picking a color, and clicking "OK" will hang the event thread in 64-bit Ubuntu 9.04 (Java 6 Update 13). Usually it takes between 2 to 20 launches of the JColorChooser before the color chooser will not launch and the UI is frozen. I cannot reproduce this using 32-bit Windows XP. I can even use the Sun Java Tutorial code and the problem occurs every time (Tutorial Link for a Color Editor in a JTable: http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TableDialogEditDemoProject/src/components/ColorEditor.java).
    Has anyone else seen this problem and found a workaround of any kind? Or has anyone tested this on 64-bit linux with Java 6 without problems? Thanks much to all for any help.

    Here is a testbed that will produce the problem for me.
    * 1) Run the testbed.
    * 2) Click the button.
    * 3) Pick a new color swatch.
    * 4) Click OK.
    * 5) Repeat steps 2-4 until the color chooser does not launch.
    * (This was between 1 and 25 times for me)
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * This class demonstrates a problem with JColorChooser.
    * I encountered this problem launching a color chooser from a
    * table cell, thus this example is based on table cell editor
    * code from the Java Tutorial (ColorEditor.java). I have added a
    * main() and removed some of the Table related noise.
    * 1) Run.
    * 2) Click the button.
    * 3) Pick a new color swatch.
    * 4) Click OK.
    * 5) Repeat steps 2-4 until the color chooser does not launch.
    * (This was between 1 and 25 times for me)
    public final class ColorChooserTest implements ActionListener
    private Color currentColor = Color.BLUE;
    private final JButton button = new JButton("Push Me");
    private final JColorChooser colorChooser;
    private final JDialog dialog;
    private static final String EDIT = "edit";
    private final JFrame frame = new JFrame("JColorChooser TestBed");
    public ColorChooserTest() {
    button.setActionCommand(EDIT);
    button.addActionListener(this);
    button.setBorderPainted(false);
    button.setBackground(currentColor);
    //Set up the dialog that the button brings up.
    colorChooser = new JColorChooser();
    dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true, //modal
    colorChooser,
    this, //OK button handler
    null); //no CANCEL button handler
    final JPanel holder = new JPanel(new BorderLayout());
    holder.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    holder.add(button, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(holder, BorderLayout.CENTER);
    frame.pack();
    public void actionPerformed(final ActionEvent e)
    if (EDIT.equals(e.getActionCommand()))
    //The user has clicked the cell, so
    //bring up the dialog.
    button.setBackground(currentColor);
    colorChooser.setColor(currentColor);
    dialog.setVisible(true);
    else
    //User pressed dialog's "OK" button.
    currentColor = colorChooser.getColor();
    button.setBackground(currentColor);
    public static void main(final String[] args)
    final ColorChooserTest x = new ColorChooserTest();
    x.frame.setSize(300, 300);
    x.frame.setVisible(true);
    }

  • Kill Execute Thread

    Is there a way to kill specific Execute Threads. We are in a situation when an
    MDB would not acknowledge specific messages and those MDBs(which run on default
    execute queue) will not terminate. We would like to kill those threads when we
    want to undeploy the app. IF there are MDBs running on other threads, then the
    app would not end gracefully. See post
    http://newsgroups.bea.com/cgi-bin/dnewsweb?utag=&group=weblogic.developer.interest.jms&xrelated=10750&cmd_thread_next.x=45&cmd_thread_next.y=11
    So the question: Is there a way to kill specific execute threads thru JMX or some
    other way?
    Thanks
    Raj

    What do you mean by "executes a script"? Is this execing a shell or is it just running some Java code?
    You can't kill a Thread if it doesn't want to be killed. The deprecated Thread.stop method will atempt to cause an asynchronous ThreadDeath exception in the thread but this is very dangerous as it can leave shared objects - including system library objects - in an unstable and unusable state.
    The preferred mechanism is cooperative termination whereby you use the Thread.interrupt method to indicate to the target thread that it should cease what it is doing, when it is safe to do so. The target thread must be responsive to interrupt requests either by directly checking Thread.interrupted, or by using methods that are themselves responsive to interrupts (typically blocking methods that will throw InterruptedException if interrupted). Some blocking methods (mainly IO operations) won't respond to interrupt, nor does the acquisition of a monitor lock, so there are never any guarantees. If the thread can stuck in an "endless loop" then something in that loop needs to check for interrupts.

  • Swing event queue, modal dialogs, event threads, etc...

    Hey all,
    So I am playing around with the focus manager, swing event thread and event queue, etc. Learned quite a bit. I am also playing around with test automation of our UI, using jfcUnit. I have written a few simple apps to play aorund with record/playback, coding tests, etc. What this thread is about though, is figuring out how modal and non-modal dialogs "take over" the event thread/queue? The reason I ask is, if I put a simple test harness like tool embeded in my app as a separate pop-up modal dialog, and from within it there is a GUI that I can use to select a "Test" to run. Now, when I run this test, jfcUnit needs to run on the main window, not within my non-modal dialog. What I am not sure of, however, is that if by using a non-modal dialog all events will go to the main event thread? I mean, I know if I mouse over my second non-modal frame (spawned from the application frame), that events will trigger for that dialog. I remember reading somewhere that modal dialogs "block" the main event queue, all left over events are given to the newly added event queue (presumably by the modal dialog) and existing left-over events get moved to the event queue. If that is the case, I am curious why events for the "old" queue are moved to the new queue if they were orginally intended for the old queue? I would think a "flush" before adding a new queue would be more appropriate so that the old queue can process all of its intended events.
    Now, I am just about to try this, but I am hoping a non-modal pop-up will not interfere with the jfcUnit running the UI of the main window. I am guessing, however, that it might. How are non-modal dialogs handled in terms of events and the event queue? Is it the same as modal dialogs? Or is there no blockage of the mainwindow event queue? If there is no blockage, than any sort of automation based on relative positions to a window may occur on the non-modal dialog, in which case it's best to hide the non-modal dialog during running of these tests.
    What are your thoughts, or better yet, knowledge of this topic? A decent explanation from a developer standpoint and not from the API's which dont give some of the more detailed info I am seeking is what I am hoping to get out of this.
    Thanks.

    Check this out. First, AWTListener has a LOT of
    different types you can register it for. I ORd all
    them together and when I ran my app, it took almost 30
    minutes for it to show up because of the huge stream
    of events being spit out via System.out. ...Yes, that doesn't surprise me in the least. There's hundreds of events that are fired around, usually unbeknownst to the user for every little thing. Lots of component and container events, in particular.
    Just make sure you OR ( using | not || ) ALL the
    "mask" values you want to watch for. That may be why
    you aren't seeing anything. When I did all that, and
    opened a menu, a ton of events came out.Maybe, I'll try that again, but I did specifically add an ActionEvent mask to get action events, and that should be all I need to get action events on buttons or menu items, and it wasn't getting them for either. It was only getting events on buttons when I used SwingEventMonitor, but not menu items.
    So I don't quite understand enough of the underlying event handling. Although, I suspect it could have something to do with the fact that these are Swing components, not AWT components (which their native peers) and it's pretty clear from AbstractButton (or was it DefaultButtonModel) how ActionEvents are fired, and they don't seem to have any connection to the code that deals with AWTListeners.
    My problem is that I kinda need a way to catch events without having a listener attached directly. Normally, I would have a listener, but there's this situation whereby an action may be triggered before I can get hold of the component to attach my listener to it. Perhaps I can get mouse press/release and just deal with it that way.
    Let me know if you did that and still didn't see what
    you were looking for. After playing with this, I am
    guessing the main reason for AWTListener is to
    register a listener for a specific type of event,
    instead of listening to them all, hence avoiding lots
    of extra overhead. Then again, the main event
    dispatcher must do a decent amount of work to fire off
    events to listeners of specific awt event types.Yes, it's definitely that. There's no point in sending events if no one is listening for it, so it does save some time.
    You are right, popup menus I think are dialogs, I
    don't know for sure, but you can access them via the
    JMenu.getPopupMenu() and JMenu.isPopupShowin().
    However, I am still not getting my test stuff working
    quite right.
    Yes, for menu popups. For a JPopupMenu on a right-click on any component (tree or whatever), I had a need to know about that from any arbitrary application (it's this GU testing app I'm working on), and since the popup menu doesn't belong to any component before it's shown, I couldn't necessarily know about it til it was displayed. I managed to use a combination of HierarchyEvents (using an AWTEventListener) and "component added" ContainerEvents. Not a simple matter, but it seems to work well.

  • Synchronize AccessBridge thread with AWT event thread?

    Hi,
    I am a beginner in Java Access Bridge.
    I am writing a program that runs with Java Web Start and uses JFC Swing. For system monitoring purpose my company uses HP OpenView. Probe Builder is used for recording a probe for the application. The probe will be run at regular intervals to check if anything is broken. As I understand Probe Builder uses Java Access Bridge to record & control the application flow.
    Without Java Access Bridge my program runs fine. But when I run it with Probe Builder I occasionally catch some exceptions that indicate that there are two threads running over my gui classes at the same time, the AWT event thread and another thread that comes from com.sun.java.accessibility.AccessBridge.run.
    Since my classes are not thread safe (like all the Swing classes) there are race conditions that result in a NullPointerException.
    My question is that how can I make sure that only one thread at a time is running over my code? Can I somehow make Java Access Bridge run with the AWT event thread? Or do I have to synchronize all my methods - I want to avoid this since I am not sure that this can be done perfectly.
    I will appreciate any help.
    Thanks
    Message was edited by:
    karneim

    Maybe there is some other way to "kill" this thread because for some specific reasons I don't think I will be able to use System.exit(). This reason is - I'm using this Java program in Lotus Notes (don't know if you have had any experience with this) and if I call System.exit() then some important clean-up (garbage collection) won't be done.

  • How to kill a Thread?

    Hello,
    My question is simple how to kill a thread.
    The background is a call to a method in a third party API, crawler4j, that locks the entire program.
    The design of crawler4j is "You should stop it when you think it's enough (ctrl+c)" but as I use it only as a step in a larger program I want to stop it programmatically and not by "ctrl+c" as they have designed the API.
    This is the locking callcontroller.start(MyCrawler.class, numberOfCrawlers);So I made a thread public class MyCrawlController extends Thread {
    public void run(){
      controller.start(MyCrawler.class, numberOfCrawlers);
    }And in my main method
    MyCrawlController mCC = new MyCrawlController();
    mCC.start();
    Thread.sleep(180000);
    //Here I want to kill the mCC and all it's threadsOne problem is that my program never terminates. Probably due too the JVM not realizing that I don't want it to count mCC and it's spawned threads as alive. Any idea on how to solve this. For now I can only exit the program with System.exit(0); and I don't want that. So I need a way to stop the mCC's threads and get the JVM not to count them. Any idea on how to solve this. Even better if they can be taken by the GC.

    Farmor wrote:
    Thanks for the answer.
    I came to think about daemons and solved the problem with mCC.setDaemon(true);Really stupid that one has to do several programs and tie them together only to kill a thread.
    As I only do this for other learning purposes and won't use this code or program after this week I will modify crawler4j, open source, and make myself a custom good method that will terminate itself and return to the main method properly.There are some fairly difficult problems with a number of aspects of concurrency if you forcibly stop threads, which is why Thread.stop() and related methods have long been deprecated.
    It's a pity that Java can't respond to kill signals (like Ctrl-C) in a tidy way. I think they're all tied up with some of the JVMs internal processes.
    In general people wind up using sockets instead of signals.

  • Flags and the Event Thread

    I was writing code for a game and I realized that the AWT event thread could change the value of a flag while I'm in the process of updating the game state. This can cause a few problems, or it could even leave events not handled because of it. I see code like this all the time as a fix to the threading issues, am I missing something or is it really a solution? I can't post the actual code as it's too long, so I created a simple example:
    import java.awt.event.*;
    import javax.swing.*;
    public class EventTest extends JFrame implements KeyListener, Runnable
         private boolean isKeyDown;
         public EventTest()
              setSize(500, 500);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setVisible(true);
              addKeyListener(this);
              new Thread(this).start();
         public void keyPressed(KeyEvent event)
              //synchronized(this)
                   isKeyDown = true;
         public void keyReleased(KeyEvent event)
              //synchronized(this)
                   isKeyDown = false;
         public void keyTyped(KeyEvent event) {}
         public void run()
              // game loop
              while(true)
                   //synchronized(this)
                        boolean cache = isKeyDown;
                        System.out.print(isKeyDown); // before
                        System.out.print(' ');
                        /* event handling, game logic, etc. done here
                           do some useless operation to simulate this */
                        long time = System.currentTimeMillis();
                        while(time + 1 > System.currentTimeMillis());
                        System.out.println(isKeyDown); // after
                        if(cache != isKeyDown)
                             System.out.println("PROBLEM!");
                        // render everything to the screen
                   try
                        Thread.sleep(100);
                   } catch(InterruptedException e) {}
         public static void main(String[] args)
              new EventTest();
    }Basically I have a game loop, where I update the game state, handle events, then draw things to the screen. Each time a key is pressed or released, I set the appropriate value to isKeyDown from the AWT event thread. The desirable output is to have the booleans equal to each other so that "false false" or "true true" is printed out on the screen constantly, but once in a while I'll get a "false true" or "true false", which is expected but obviously not wanted.
    So one solution is right there commented out (synchronizing), though most people seem to avoid it. I see everybody using flags like this, so I'm wondering if I'm missing some obvious solution to the problem or if it's really even that big of a deal. I don't see any other fix, but that's why you're all here. ;)
    Thanks.

    Swing related questions should be posted in the Swing forum.
    I converted your simple example to use a Swing Timer instead of a while(true) loop with a Thread.sleep. I experienced no problems as expected since all the code will be executed in the Event Dispatch Thread (EDT).
    Of course using this approach could make the game less responsive if your game logic is extensive and hogs the EDT, but given that you try to invoke your game logic every 100 millisecond I assume it can't be that extensive.
    Anyway here is the code I used as a test:
    import java.awt.event.*;
    import javax.swing.*;
    public class EventTest extends JFrame implements KeyListener, ActionListener
         private boolean isKeyDown;
         public EventTest()
              setSize(500, 500);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setVisible(true);
              addKeyListener(this);
              new Timer(100, this).start();
         public void keyPressed(KeyEvent event)
              isKeyDown = true;
         public void keyReleased(KeyEvent event)
              isKeyDown = false;
         public void keyTyped(KeyEvent event) {}
         public void actionPerformed(ActionEvent e)
              boolean cache = isKeyDown;
              System.out.print(isKeyDown); // before
              System.out.print(' ');
              /* event handling, game logic, etc. done here
                 do some useless operation to simulate this */
              long time = System.currentTimeMillis();
              while(time + 1 > System.currentTimeMillis());
              System.out.println(isKeyDown); // after
              if(cache != isKeyDown)
                   System.out.println("PROBLEM!");
         public static void main(String[] args)
              new EventTest();
    }

  • AWT idle event thread?

    Does anyone have an example of how to create an
    AWT "busy" Dialog? I'd like to have a modal dialog
    come up that says my applet is doing some task,
    and when that task is complete, the Dialog should
    go away. So, typically, the user would not click
    anything in the dialog, it would just go away when
    the task finishes.
    What I now do is call show() from the event thread,
    and also span a new thread to do the actual work and
    when the work is complete, my new thread (not
    the AWT event thread) gets rid of the busy dialog.
    However, this seems to result in a hung UI most
    of the time with IE.
    I suspect maybe if the event thread got rid of the
    Dialog instead of my other thread the UI hang might
    not happen.
    Is there a way I can create tell AWT to run an idle
    thread (ie, when it's not doing anything)? If I could
    do that, then I could let the AWT event thread get
    rid of my dialog.
    Thank you!

    First of all, there is no way to create a modal dialog for an applet. Because the constructor of modal dialog needs a Dialog or Frame object as its owner. Unfortunately, the applet subclasses Panel that is in the hierarchy that is other than Dialog and Frame's. You can think in this way the applet does not own the browser's window.
    The dialog created by an applet sometimes get UI frozen. The reason is that the thread you created for the dialog is in the same thread group, sun.applet.AppletThreadGroup where the dialog thread can not get enough time slices to run.
    What I have done to solve this problem is to create the dialog thread under main thread group. I list the source code below for your reference.
    ThreadGroup group = Thread.currentThread().getThreadGroup();
    while(!group.getName().equals("main"))
    group = group.getParent();
    new Thread(group, this, "BusyDialog").start();

  • Killing a thread easily?

    Hello, I'm working with a thread class that looks like this:public void run() {
         while (true) {
              Socket client = aServerSocket.accept();
              // do stuff
    }The problem is kind of obvious, as it is, it never stops unless you kill the VM, eventually leading to dozens of threads. Even if I changed the loop variable, the thread would still hang around while accept() blocked for input. I want to kill it when I know it's useless. My first attempt was:     while (!Thread.interrupted()) {and then calling interrupt() on the thread - oops! - serversockets aren't interruptable, so the thread still never stopped. I was going to come here and post then, but I went back and read the api for server sockets again, and found that calling close() on the socket will interrupt the blocking accept(). So:     while (!aServerSocket.isClosed()) {Unfortunately, I'm not sure if that actually works, or not, because my app which used to take up < 1% of CPU time when running was now taking more than 50%, so I shut it down - at least when there are lots of threads, they are all sleeping and don't eat the cpu :(
    Does anyone have any suggestions on how to stop threads ?

A: Killing a thread easily?

ejp: I'm not sure what you're referring to, but from the ServerSocket api:
"close() : Closes this socket. Any thread currently blocked in accept() will throw a SocketException."
There are other things in the 'do stuff' part of the loop that can throw exceptions, but I don't want to break out of the loop. I omitted the try around 'accept' and 'do stuff' for simplicity in my original diagram. I tried rearranging my try statements like so:
try {
     while(true) {
          Socket client = aServerSocket.accept();
          try {
               // do stuff
          } catch ()
} catch ()So that if the accept call threw an exception, it would drop out of the while loop. Unfortunately, when I tried running this the program took up >25 % of my CPU time to run, instead of < 1 % as usual, like my third try above.
hiwa: Sorry I didn't explain more clearly. Several of these threads are being spawned to listen to multiple sockets. Sometimes the connection gets dropped, due to lag or internal reasons, and it reconnects on a new socket with a new thread, but the old socket and thread are still hanging around because it's stuck in the while(true) loop and accept blocks indefinately.

ejp: I'm not sure what you're referring to, but from the ServerSocket api:
"close() : Closes this socket. Any thread currently blocked in accept() will throw a SocketException."
There are other things in the 'do stuff' part of the loop that can throw exceptions, but I don't want to break out of the loop. I omitted the try around 'accept' and 'do stuff' for simplicity in my original diagram. I tried rearranging my try statements like so:
try {
     while(true) {
          Socket client = aServerSocket.accept();
          try {
               // do stuff
          } catch ()
} catch ()So that if the accept call threw an exception, it would drop out of the while loop. Unfortunately, when I tried running this the program took up >25 % of my CPU time to run, instead of < 1 % as usual, like my third try above.
hiwa: Sorry I didn't explain more clearly. Several of these threads are being spawned to listen to multiple sockets. Sometimes the connection gets dropped, due to lag or internal reasons, and it reconnects on a new socket with a new thread, but the old socket and thread are still hanging around because it's stuck in the while(true) loop and accept blocks indefinately.

  • Killing a Thread

    In recent versions of the JDK they deprecated the stop() and destroy() methods. They did so because those methods can kill a thread in a "dirty" way. The replacement approach is to have a while(isRunning){} loop in the run() method and to set isRunning to false via a call to another method.
    I have a scenario that can be described as follows (taking some liberties with syntax):
    public void run(){
    while(isRunning){
    JobInterface job = ... code to instantiate the job via reflection.
    job.execute();
    isRunning = false;
    Here, although the interface is standard, the job is one of many possible applications written by other people and without access to their source code. The JobInterface is already defined and there are many applications already in production that use it - in other ways we can't expect to change the code of the reflected jobs. Further, setting isRunning to false while the job is executing its execute() method (possibly for hours) isn't going to help.
    So the question here is, how to kill a thread like this one... while it is still waiting for job.execute() to end?

    bmelloni wrote:
    I only need the forced thread stop for those jobs that cannot be modified to comply with the above. At that point whatever consequences there are for those jobs will have to be accepted. If resources (i.e.: database) are left in messed up states... tough. It will have to be handled then (and maybe it will give incentive to make those black-box jobs compliant).I doubt it. Unless someone quite high-up is informed, these things are often shelved until something breaks. My suggestion would be to put your (our?) concerns in writing, and make sure you get a reply in kind from your management before you do anything. Once the finger-pointing starts, it's usually the sharp end that suffers.
    But we aren't even planning to use this capability to stop threads unless our server is about to crash - in which case the consequences would have been the same.Better make sure it's VERY difficult to do accidentally then.
    In other words, don't worry... we are not stupid.I don't think anyone said stupid...Naive, maybe.
    Winston

  • Thread being aborted sharepoint 2013

    Hi All,
    I am receiving the below error "Thread being aborted" when i try to open my dev url. I have no idea about the area(ThirdSPS2010) which is throwing error. As the production was set up by third party and i just took back up of the url and also the
    back up of custom webparts and restored in development environment. I am struck with this error now :(
    06/25/2013 14:06:17.45     w3wp.exe (0x22A4)                           0x13DC    ThirdSPS2010               
         Error                             00000    Unexpected    Thread was
    being aborted.    b6c1289c-d07c-a0de-44ea-088cb42c35e3
    Above this i can find multiple Distributed cache warnings as below
    SharePoint Foundation             DistributedCache                  ah24w    Unexpected  
     Unexpected Exception in SPDistributedCachePointerWrapper::InitializeDataCacheFactory for usage 'DistributedLogonTokenCache' - Exception 'System.InvalidOperationException: SPDistributedCachePointerWrapper::InitializeDataCacheFactory - No cache hosts are
    present or running in the farm.     at Microsoft.SharePoint.DistributedCaching.SPDistributedCachePointerWrapper.InitializeDataCacheFactory()'.
    Can someone guide what is the reason for these errors :(
    Thanks in advance
    Ranjani.R

    Unlike other service instances, though, the Distributed Cache Service Instance should either be installed *and* online on a SharePoint server, or not installed at all. If the service instance is stopped (disabled) but not uninstalled, details about the associated
    Cache Host stay in the Cache Cluster Config store, which can cause problems.
    For this reason, the Distributed Cache Service Instance should never be stopped via the Services on Server page in Central Administration or via Stop-SPServiceInstance in PowerShell. A special cmdlet, Remove-SPDistributedCacheServiceInstance, is available
    to stop *and* uninstall the local Distributed Cache Service Instance from a SharePoint server. This cmdlet, and its complement Add-SPDistributedCacheServiceInstance, should be used instead of Stop- and Start-SPServiceInstance for managing the local Distributed
    Cache Service Instance.
    from
    http://blogs.msdn.com/b/besidethepoint/archive/2013/03/27/appfabric-caching-and-sharepoint-2.aspx

  • Best way to stop or kill a thread

    hi what would say is the best way to kill a thread in this situation.
    1. I have 200 threads
    2. Each Thread has a reference stored in a hashtable example;
    for( int i=0; i<200; i++){
    Thread t = new exThread(i);
    hashtable.put(Integer(i) , t );
    t.start();
    each thread is running in an infinite while loop.
    now what would you say is the best way to kill the thread from this parent class.
    One thought of mine is to access get the reference and call stop.
    example;
    Thread tRef = hashtable.get(Integer(100));
    tRef.stop();
    In the stop method i would clear up whatever it was doing - release resources properly and - when it goes out of the stop scope , i'm guessing it would be destroyed.
    Any thoughts or other recommendations ?
    Stev

    Limeybrit is correct....the way Sun recommends (and which I use) is a boolean at the top of your runnable code. If false, you simply return and don't hit any of the other code in the runnable method.
    At the end of your run process, you simply set your Thread to null and wait for the garbage collector to clean up.

  • How to invoke the shutdown event tracker when running restart-computer

    In Windows command shell, it is possible to run shutdown /d to specify a reason code and /c to enter a comment into the shutdown event tracker to log why a shutdown was being performed.
    I'm not seeing an equivalent parameter for the restart-computer cmdlet in PowerShell.  Is it possible to invoke the shutdown event tracker when running restart-computer?

    help restart-computer 
    says no.  There's nothing wrong with using native commands, in a number of cases they are better than what PS provides.
    I hope this post has helped!

  • Maybe you are looking for

    • Coldfusion 8: Onblur doesn't fire on autosuggest cfinput

      Hello, I have a problem using the autosuggest cfinput. Here is the sample of my code. <cfinput name="item_number" maxlength="20" type="text" maxResultsDisplayed="20" autosuggest="cfc:Inventory.model.lookupRoom.lookup({cfautosuggestvalue})" value=#get

    • Adapter Module not working in Sender Communication Channel working in recie

      Hi I have written one adapter module. IF i give that Adapter Module in Sender Communication channel its not working. If i give that in Reciever Communication Channel its working. If i mention in both the channels then its working in sender communicat

    • SRM with PPS = Extended Classic Scenario

      Does SRM Procurement for Public Sector (PPS) require Extended Classic Scenario? If so, could some one refer me to an official documentation that states such? Thanks.

    • SAPBEXgetConnection doesn't return proper values when BEX is open via RRMX

      had to put a lot of interactivity in some workbook based on the user profile and going far beyond the simple authorisation objects. Following the advice of some specialists such as Peter Knoer, I used the following code to get the user connection det

    • Can't run my java programs

      I installed J2SE v 1.4.2_04 SDK on my computer. I'm using textpad to write my programs. After i'm done writing my programs in can compile them on textpad and javac in command prompt. But when i try to run my program using java HelloWorld and textpad