Killing a Thread that runs a C code

Hi,
In my Java application, i use a library written in C++ using JNI. The tasks that are executed by the C library sometimes take a lot of time, so I was considering adding an option for the user to be able to stop it. As these tasks are running in a thread, i was wondering whether there is a way to safely do this?
I have searched the forum, but did not manage to find some post with similar problem. As far as I could see, stopping a thread in general is not safe...
Suggestions guys?
Thanks

shashi_rajak wrote:
you can stop the thread by setting the value of thread to null.---------------> the thread will not be stopped immediately.So setting it to null won't change anything at all. Yes, that's correct, but that isn't what you said previously.
better put a guarded block in the thread code .What's a guarded block?
so that thread will not process the rest of code.Ah, you mean that you need some kind of flag, latch or other way to signal. That's correct, but you never said that (you actually still haven't said that)
>
>
user can again start the thread by starting the thread.-----------------> its mean by creating a new thread object. We aren't mind readers. Calling start of a new thread will of course work, but that isn't what you said.
since you cannot start a already started thread its throws invalid State Exception.Yes, we knew that. That's why we corrected you.
this current forum is not for beginner . Eh. Hmm.. Ok, so I registered in 2000, and have quite many posts, and you came to the conclusion that I'm a beginner?
It has the heading Java Programming " not "New to java". please use your brain.Did you use yours?

Similar Messages

  • Cannot kill a session that is running a query on a linked server in SQL Server 2008 R2

    Hi,
    Cannot kill a session that is running a query on a linked server  in SQL Server 2008 R2.
    When I try to kill, it status shown as "KILLED/ROLLBACK"
    I have facing the issue from long back. I searched many and none of them worked for me
    Any help is greatly appreciated
    Thanks
    Jaison
    Carver

    I guess its stuck, can you see some blocking or any other process blocking the rollback.
    can you check rollback status using below command. Or you can use sp_who2 and check status column
    select percent_complete,estimated_completion_time from sys.dm_exec_requests
    where spid=xxx
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it.
    My TechNet Wiki Articles

  • Hello i am having a problem in my 4s that it dosent run any USSD code it goes on calling , can any one help me i am mack from Karachi Pakistan

    Hello i am having a problem in my 4s that it dosent run any USSD code it goes on calling , can any one help me i am maqsood  from Karachi Pakistan

    Ok so I've done what you said and this is what it's come back ....
    I don't know that these are the errors , but they're the things which don't look right ...
    Throughout the shut down there is a recurring line ;
    It says ;
    Com.apple.launchd 1 0x100600e70.anonymous.unmount 301 PID still valid
    Then there are 2 more which I think are related ;
    Com.apple.securityd 29 PID job has I overstayed its welcome , forcing removal.
    Then the same with fseventd 48 and diskarbitrationd 13
    Oh and on Launchd1 : System : stray anonymous job at shut down : PID 301 PPID13 PGID 13 unmount...
    Then the last process says "about to call: reboot (RB_AUTOBOOT).
    Continuing...
    And stops ...
    Hope this means something to you ... Thanks again for your help so far :-)

  • What are changes between FP 10.0.42.34 and 10.0.45.2 that could cause AS2 code to run differently?

    Hi, I am trying to debug a large Flash reading literacy application which is written in AS2. Everything works in 10.0.42.34. When our school customers upgrade to 10.0.45.2 they get blocked from proceeding with training.
    The main movie has loaded an application to run a sequence of tutorial movieclips, driven by an xml input.
    The application waits for each background plus movie to load and the plays the movie.
    It then unloads the movie and background and proceeds to the next movie/background.
    I am running the debugger in CS4 in both FP 10.42.34 and FP 10.0.45.2, the two [UnloadSWF] trace outputs happens in both, but the next step is missed. I am delving into the code right now, but I hope that there may be a hint in the changes made.
    I see no errors or security sandbox issues in the trace output.
    Can someone tell me what main changes there are in FP 10.0.45.2 that could cause AS2 code to run differently?
    Currently we are going to tell our customers that they must downgrade Flash Player to keep their kids learning to read.
    Thanks,
    Sue W.

    All these bug reports are probably describing same problem:
    http://bugs.adobe.com/jira/browse/FP-3993
    http://bugs.adobe.com/jira/browse/FP-4137
    http://bugs.adobe.com/jira/browse/FP-4121
    Not yet any word from Adobe that this is considered a bug worth fixing.
    I would also like to add that the bug failing to load or run older AS1/2 swfs is present in both latest release version FP 10.0.45.2 and FP 10.1.51.95 (beta 3). So it does not look like it has been fixed with 10.1

  • I have old MacBook running OS 10.6.8 I was told in Apple Genius Bar that I need a code from apple support to upgrade to 10.7.   Apple support will not help because I am have their support plan.  Can some one help?

    I have old MacBook running OS 10.6.8 I was told in Apple Genius Bar that I need a code from apple support to upgrade to 10.7.   Apple support will not help because I am have their support plan.  Can some one help?

    hi Samberl
    thanks a lot for the fast reply.
    I was dragging folders from main folders on the laptop-desktop  onto the external drive icon - to copy them across....
    Your suggestion sounds very promising -  I didn't know about 'cloning'.
    Yes the idea is to backup the laptop -    I thought I would just move it all now, new - and then keep saving/dragging physically   across to the new drive myself each day or two...
    Would this be the sizeof the internal hard drive = c.500 gb  ?   =   under the HD icon on desktop is written  : 
    " 499.76gb , 311.5 gb free  " 
    I can erase and start agin on the new external drive - so this plan is to make two partititions, rather than the one at present, and make one of them 500 gb ?
    I have found CCC [carbon copy cloner] googling - looks good.
    When CCC site says it backs up  the hard drive - would this  mean all my files  [over 100 gb] that are mostly  in folders on the desktop, plus the others in itunes, iphotos etc found in the HD icon,  would all copy across successfully [wherever they are in the computer ]  ?
    thanks again, hope you can clarify these things and then I will go for it. 
    It would be great and amazing if this 'lack of permission' message doesn't show up in the process of doing this ccc transfer - hopeful!
    Julie

  • Code that Runs for All Exceptions

    I have PL/SQL code that I want to run for any exception that I might encounter in a given block of code.  Basically, this code resets a package variable that was set earlier in the block.  So if my block is running and it encounters an exception, I want to reset the package variable, no matter what the exception.
    So do I need to run this reset code under every possible WHEN clause to be sure that I've hit all the possibilities?
    I think I can probably create a nested block that raises the error into the main block so that the main block can have just a single WHEN OTHERS clause, wherein I can execute my single reset statement; however, this seems like overkill.  Is there any simpler way to do this?
    Thanks for any help you can give.
    Wayne

    Hi, Wayne,
    201cbc0d-57b2-483a-89f5-cd8043d0c04b wrote:
    I have PL/SQL code that I want to run for any exception that I might encounter in a given block of code.  ...
    That's a good way to get into a lot of trouble.  That's kind of like saying "My daughter is supposed to be home from school by 4:00.  If she's not, ignore it and keep working."
    Your code should check for mistakes that you expect will happen (e.g., no data in a table, an invalid DATE, or a string in the wrong format).  Sometimes, an EXCEPTION handler is a good way to check for those expected errors.  But if anything that is not expected happens, you ought to know about it.

  • When my thread starts running, at that time keylistener is not working.

    when my thread starts running, at that time keylistener is not working.
    plz reply me.

    //FrameShow.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.awt.event.*;
    import java.util.*;
    public class FrameShow extends JFrame implements ActionListener,KeyListener
         boolean paused=false;
         JButton stop;
         JButton start;
         JButton exit;
         public IncludePanel CenterPanel;
         public FrameShow()
    CenterPanel= new IncludePanel();
              Functions fn=new Functions();
              int height=fn.getScreenHeight();
              int width=fn.getScreenWidth();
              setTitle("Game Assignment--Santanu Tripathy--MCA");
              setSize(width,height);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              show();
              initComponents();
              DefaultColorSet();
              this.addKeyListener(this);
         this.setFocusable(true);
         public void initComponents()
              Container contentpane=getContentPane();
              //Creating Panel For Different Side
              JPanel EastPanel= new JPanel();
              JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
              //CenterPanel = new IncludePanel();
              //IncludePanel CenterPanel= new IncludePanel();
              EastPanel.setPreferredSize(new Dimension(100,10));
              WestPanel.setPreferredSize(new Dimension(100,10));
              NorthPanel.setPreferredSize(new Dimension(10,100));
              SouthPanel.setPreferredSize(new Dimension(10,100));
              //CenterPanel.setPreferredSize(new Dimension(200,200));
              //Adding Color to the Panels
              NorthPanel.setBackground(Color.green);
              SouthPanel.setBackground(Color.orange);
              CenterPanel.setBackground(Color.black);
              //Creating Border For Different Side
              Border EastBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border WestBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border NorthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border SouthBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              Border CenterBr = javax.swing.BorderFactory.createEtchedBorder(Color.cyan, Color.red);
              //Creating Components For East Panel
              JLabel left= new JLabel("LEFT");
              JLabel right= new JLabel("RIGHT");
              JLabel rotate= new JLabel("ROTATE");
              left.setForeground(Color.blue);
              right.setForeground(Color.blue);
              rotate.setForeground(Color.blue);
              //Creating Components For West Panel
              ButtonGroup group = new ButtonGroup();
              JRadioButton rb1 = new JRadioButton("Pink",false);
              JRadioButton rb2 = new JRadioButton("Cyan",false);
              JRadioButton rb3 = new JRadioButton("Orange",false);
              JRadioButton _default = new JRadioButton("Black",true);
              rb1.setForeground(Color.pink);
              rb2.setForeground(Color.cyan);
              rb3.setForeground(Color.orange);
              _default.setForeground(Color.black);
              //Creating Components For North Panel
              JLabel name= new JLabel("Santanu Tripathy");
              name.setForeground(Color.blue);
              name.setFont(new Font("Serif",Font.BOLD,30));
              //Creating Components For South Panel
              start = new JButton();
              stop = new JButton();
              exit = new JButton();
              start.setToolTipText("Click this button to start the game");
              start.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              start.setText("START");
              start.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              start.setMaximumSize(new java.awt.Dimension(90, 35));
              start.setMinimumSize(new java.awt.Dimension(90, 35));
              start.setPreferredSize(new java.awt.Dimension(95, 35));
              if(paused)
                   stop.setToolTipText("Click this button to pause the game");
              else
                   stop.setToolTipText("Click this button to resume the game");
              stop.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              stop.setText("PAUSE");
              stop.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              stop.setMaximumSize(new java.awt.Dimension(90, 35));
              stop.setMinimumSize(new java.awt.Dimension(90, 35));
              stop.setPreferredSize(new java.awt.Dimension(95, 35));
              exit.setToolTipText("Click this button to exit from the game");
              exit.setFont(new java.awt.Font("Trebuchet MS", 0, 12));
              exit.setText("EXIT");
              exit.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(3, 5, 3, 5), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
              exit.setMaximumSize(new java.awt.Dimension(90, 35));
              exit.setMinimumSize(new java.awt.Dimension(90, 35));
              exit.setPreferredSize(new java.awt.Dimension(95, 35));
              //Adding some extra things to the Panels
              group.add(rb1);
              group.add(rb2);
              group.add(rb3);
              group.add(_default);
              //Adding Component into the Panels
              EastPanel.add(left);
              EastPanel.add(right);
              EastPanel.add(rotate);
              WestPanel.add(rb1);
              WestPanel.add(rb2);
              WestPanel.add(rb3);
              WestPanel.add(_default);
              NorthPanel.add(name);
              SouthPanel.add(start);
              SouthPanel.add(stop);
              SouthPanel.add(exit);
              //Adding Border Into the Panels
              EastPanel.setBorder(EastBr);
              WestPanel.setBorder(WestBr);
              NorthPanel.setBorder(NorthBr);
              SouthPanel.setBorder(SouthBr);
              CenterPanel.setBorder(CenterBr);
              //Adding Panels into the Container
              EastPanel.setLayout(new GridLayout(0,1));
              contentpane.add(EastPanel,BorderLayout.EAST);
              WestPanel.setLayout(new GridLayout(0,1));
              contentpane.add(WestPanel,BorderLayout.WEST);
              contentpane.add(NorthPanel,BorderLayout.NORTH);
              contentpane.add(SouthPanel,BorderLayout.SOUTH);
              contentpane.add(CenterPanel,BorderLayout.CENTER);
              //Adding Action Listeners
              rb1.addActionListener(this);
              rb2.addActionListener(this);
              rb3.addActionListener(this);
              _default.addActionListener(this);
              exit.addActionListener(this);
              start.addActionListener(this);
    try
              start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
    try
              stop.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        paused=!paused;
                        if(paused)
                             start.setToolTipText("Click this button to resume the game");
                             stop.setText("RESUME");
                        else
                             start.setToolTipText("Click this button to pause the game");
                             stop.setText("PAUSE");
    CenterPanel.pause();
    catch(Exception e)
    {System.out.println("Exception is attached with sart button exp = "+e);}
         public void DefaultColorSet()
              getContentPane().setBackground(Color.white);
         public void actionPerformed(ActionEvent AE)
              String str=(String)AE.getActionCommand();
              if(str.equalsIgnoreCase("pink"))
                   CenterPanel.setBackground(Color.pink);
              if(str.equalsIgnoreCase("cyan"))
                   CenterPanel.setBackground(Color.cyan);
              if(str.equalsIgnoreCase("orange"))
                   CenterPanel.setBackground(Color.orange);
              if(str.equalsIgnoreCase("black"))
                   CenterPanel.setBackground(Color.black);
              if(str.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void keyTyped(KeyEvent kevt)
    //repaint();
    public void keyPressed(KeyEvent e)
              System.out.println("here key pressed");
              //CenterPanel.dec();
         public void keyReleased(KeyEvent ke) {}
    }//End of FrameShow.ja
    //IncludePanel.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Graphics.*;
    import java.awt.Dimension;
    import java.awt.geom.Dimension2D;
    import java.util.*;
    import java.util.logging.Level;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class IncludePanel extends JPanel implements Runnable
    int x=0,y=0;
    int color_1=0;
    int color_2=1;
    int start=0;
    Thread th;
    Image red,blue,green,yellow;
    java.util.List image;
    static boolean PAUSE=false;
         public IncludePanel()
         red= Toolkit.getDefaultToolkit().getImage("red.png");
         blue= Toolkit.getDefaultToolkit().getImage("blue.png");
         green= Toolkit.getDefaultToolkit().getImage("green.png");
         yellow= Toolkit.getDefaultToolkit().getImage("yellow.png");
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void dec()
         System.out.println("in dec method");
         x=x+30;
    public void draw(Graphics g)
              g.setColor(Color.red);
              int xx=0,yy=0;
              for (int row=0;row<=12;row++)
                   g.drawLine(xx,yy,180,yy);
                   yy=yy+30;
              xx=0;
              yy=0;
              for (int col=0;col<=6;col++)
                   g.drawLine(xx,yy,xx,360);
                   xx=xx+30;
              if(color_1==0)
                   g.drawImage(red, x, y, this);
              else if(color_1==1)
                   g.drawImage(blue,x, y, this);
              else if(color_1==2)
                   g.drawImage(green,x,y, this);
              else if(color_1==3)
                   g.drawImage(yellow,x,y, this);
    x=x+30;
              if(color_2==0)
                   g.drawImage(red, x, y, this);
              else if(color_2==1)
                   g.drawImage(blue,x,y, this);
              else if(color_2==2)
                   g.drawImage(green,x,y, this);
              else if(color_2==3)
                   g.drawImage(yellow,x,y, this);
    x=0;
    public void drawCircle( )
         th=new Thread(this);
         th.start();
         public void pause()
              if(PAUSE)
                   th.resume();
                   PAUSE=false;
                   return;
              if(!PAUSE)
              PAUSE=true;
         public synchronized void run()
              Random rand = new Random();
              Thread ani=Thread.currentThread();
              while(ani==th)
                   if(PAUSE)
                        th.suspend();
                   if(y==330)
                        color_1 = Math.abs(rand.nextInt())%4;
                        color_2 = Math.abs(rand.nextInt())%4;
                        if(color_1==color_2)
                             color_2=(color_2+1)%4;
                        y=0;
                   else
                        y=y+30;
                   repaint();
                   try
                        Thread.sleep(700);
                   catch(Exception e)
         }//End of run
    i sent two entire program

  • Add code behind functionality that run when the user view the SP 2013 content pages

    I need to add code behind functionality that run when the user view the SP 2013 content pages, What is the best approach to do that?
    is it add Delegate Control to master page?
    is it add code behind to master page?
    is there an event reviver for that?
    Your answer will be highly appreciated

    Hi,
    According to me, for code behind stuff
    Create master page(using module etc..), have the required placeholders in it.
    Then, create a page that inherit from this master page, now you can use that placeholder in you page.
    Lastly, place web parts in that placeholder. So, code behind will come with that master page .
    Hope it helps.
    Thanks
    -Rahul

  • Reading front panel of a VI that runs as a thread without using globals

    Hi Labviewans,
    I have a main VI that runs another VI as a thread. I would like to read some data on the thread-VI's front panel from the main VI without using global variables. The traditional way could be by writing the thread-VI's data to globals and then read by the main VI.
    Is there anyway not using globals to solve this matter??
    many thanks.

    Well if you mean not using the traditional globals yes. You can write the values to a vi containing an uninitialized shift register, also known as a LV2 style global, you can create control references for the controls of interest and then use them, with property nodes to read the values, you can write the values into a queue to be read elsewhere in your program. Globals, while not usually considered the optimal answer, are also not forbidden. They just should be used carefully. If you are only writting to the global from within the sub-vi, then the big concern of race conditions, etc., are not an issue. Initialize them to a desired state early in your program (before the sub-vi is launched) and then only write to them from the one location.
    P.M.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

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

  • 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

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

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

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

  • How many  threads are running?

    here's the code... i am trying to understand, at each point, how many threads are running:
    I understand that one thread belongs to the caller of the start()
    & at the same time there is another thread belonging to the instances of each thread (thread1, thread2, thread 3 etc.)
    1public class ThreadTester {
    2   public static void main( String args[] )
    3   {
    4      PrintThread thread1, thread2, thread3, thread4;
    5
    6      thread1 = new PrintThread( "thread1" );
    7      thread2 = new PrintThread( "thread2" );
    8      thread3 = new PrintThread( "thread3" );
    9      thread4 = new PrintThread( "thread4" );
    10
    11      System.err.println( "\nStarting threads" );
    12
    13      thread1.start();
    14      thread2.start();
    15      thread3.start();
    16      thread4.start();
    17
    18      System.err.println( "Threads started\n" );
    19   }
    }can you tell me if i am counting the number of threads in existance correctly...
    LINE#.....CALLER...START...TOTAL THREADS
    13..............1.........1.......2
    14..............1+1......1+1.....4
    15..............2+1......2+1.....6
    16..............3+1......3+1.....8
    so by the time line 16 executes i have a total of 8 threads,
    4 threads belonging to each caller plus
    4 threads created by start()
    or is it
    LINE#.....CALLER...START...TOTAL THREADS
    13..............1........1........2
    14..............1........1+1.....3
    15..............1........2+1.....4
    16..............1........3+1.....5
    after line 16 executes does the caller thread die, thus leaving only a total of 4 threads?
    there is only one thread belonging to the caller at line 13(plus the thread it creates).
    at the start of line 14, the previous callers thread is dead & now a new thread is created that belongs to the caller on line 14... etc.

    well, i realize at the end there would be 4 threads but im trying to get my head around this explanation in the book:
    "A program launches a threads executioin by calling the threads start method, which in turn call the run method. After start launches the thread, start returns to tis caller immediately. The caller then executes concurrently with the lauched thread." there fore if i have 2 concurrent processes, are there 2 threads running????
    now having said the above, my question was:
    for each line,
    how many threads are in existance at
    line13
    line14
    line15
    line16
    thanks.

Maybe you are looking for

  • 24" LED Cinema display doesn't display screen saver.

    I have my MacBook Pro set to display a screen saver- (flurry). The MBP alone functions as desired. When plugged into the Cinema display, which is 90% of the time, it has only appeared maybe once or twice since purchased, even after Snow Leopard was i

  • Sending PDF by mail but PDF is not opening because of PDF Size.

    Hi all, I am sending a sapscript in PDF format through Email. Sapcript is going fine in PDF file for a test case in which file size is small but for PDF files where file size is Big in the mail while opening the file PDF is giving an Error message  t

  • Error: Not Enough RAM to Open Small Files

    MacBook5,2 Macintosh OSX 10.6.3 4GB RAM NVIDIA GeForce 9400M - 256MB Adobe Photoshop CS4 Extended (11.0.1) I am rendering TIFF files out of Maya that are 11880 x 3400 pixels.  The file size ranges between 100 - 160 MB.  Whenever I attempt to open one

  • Container's validate does not update removal

    the validate() method does not update the display to show the remval of a component from a container. A way to go around: use repaint() instead. Please see the following code: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import ja

  • Menu Exit for VT02n

    Hi, i want to add a SELECT ALL button in the split deliveries screen of shipment. (VT02n->Deliveries->Split Deliveries). I have no clue how to do that. Is there any menu exit for doing this. Can anyone kindly help me in this? regards, Pavan.