Force *Untrusted* Thread to Stop

My application is running untrusted code from an external source and must force it to stop after a certain amount of time. At first I thought I would cheat and call the deprecated method Thread.stop(). I am aware of the dangers in calling Thread.stop(), but all of the alternatives to Thread.stop() that I have found assume control over the thread being stopped, which is not the case with my application. However, even this will not work because the untrusted code could start its own thread with an infinite loop, and I would not have access to that thread to be able to stop it.
The only way I can think to handle this is to start a new OS process, with a new JVM, just to run the thread. When I want to terminate the thread I can simple call System.exit() from within that virtual machine. Is there a less resource-intensive solution?
I have no moral objection to using Thread.stop() to solve this; the untrusted code will run with a SecurityManager tightly controlling its access to resources, so I am not worried about the problems described in the deprecation explanation of Thread.stop() (and even if there are problems, they would have to be big problems to be worse than starting 1 million infinite loops and choking my server). For instance, is there a way to produce all the descendant threads produced by a given thread? Is there a sandbox in which the code can be run (and stopped at my command) that is lighter than an entirely new virtual machine?
Thank you,
Dave

If the unsafe code could start a thread I suggest your thread should be in a new ThreadGroup which you can use to shutdown all threads that get created.
pexatus wrote:
alan_mehio wrote:
Hi,
The stop method has been deprecated and it is not recommended to be used since it is not safe. your code is working because of the backward compatiblity ( still works on Java 6). Again this method should not be used since it causes to unlock all the monitors by this thread and it may keep the locked objects by this thread with an unconsistant state. I understand that Thread.stop() is deprecated and unsafe in the general case where the Thread being stopped can do anything. Since the untrusted code I am running can be locked down with a SecurityManager, it seems as if there should be a way to lock it down enough that the problems inherent in Thread.stop() will not appear.You have to test it to see. It may be that there is a small but acceptable leak. How often do you restart your application?
To use your example (which is also the only example I can find online for why not to use Thread.stop(), though other unstated examples may invalidate my claim), if the code in the Thread cannot access any object that was not created within that Thread or one of the Threads running under its ThreadGroup, and if my code does not attempt to access any of those objects, then it is not a problem to leave those objects in an inconsistent state. Since any thread that might be using them will be stopped at the same time, it will not matter that the objects are inconsistent.The problem I believe is resources which require an explicit call to be made to clean them up. This includes Threads, Sockets, Files (including log files), JDBC resources. If you kill a process, all reaources get cleaned up by the OS, but if you kill a thread, there is no guarantee any of these resources will be cleaned up.
>
Now you are executing another application inside you application which is not safe.Then what is the purpose of the Java security model? I thought that the whole premise was that untrusted code could be run. The examples online are largely about running untrusted applets over the internet on a trusted client browser, but I see no reason I cannot use the same idea to secure a part of my application.The security model applies globally, not just your untrusted code. Any operation you allow for your application to operate is a security whoel for your untrusted code to exploit.
>
What is the relation of a thread with the application execution.
Does the unsafe application get executed inside a sepearate thread from your main application? if yes , have you thought of using ExecutorService where you can submit a Callable into the executor service and it returns a Future. You can cancel the returned Future.Canceling the returned Future uses Thread.interrupt to try to stop the thread. Using Thread.interrupt requires control over the code being interrupted. Since I don't have control over the code being interrupted, I cannot use it. I don't get that. If you are willing to kill the thread, I don't see the problem with give the thread a chance to shutdown gracefully. I have found that an interrupt does stop many third party threads and so I give the thread a few second to shutdown (interrupt followed by a join with a timeout) and only kill it if it doesn't.
Try creating a FutureTask with an infinite loop (without any polling of the interrupted status of the Thread) and canceling it after it has gotten started; it will not, in fact, be canceled.
If anyone knows of a way to stop code over which I do not have control, without using Thread.stop(), then I would appreciate hearing about it. The only way I can think of is to run a separate JVM, and kill it with System.exit, but as I said, this has much overhead.Another option is to use reflection hack an internal variables/methods which would shutdown the thread. This would require some investigation (such as a debugger) which I have found usually leads me to some undocumented/poorly documented public method. :)

Similar Messages

  • Application threads were stopped for a long time

    Hi, We have got the following problem.
    application threads were stopped for a long time after Minor GC hava finished. Minor GC takes usally less than 1sec but a time application threads were stopped tekes often 100 sec.
    What's jvm doing then? alternatively we want to get more information when Minor GC occured.
    gc.log
    33919.643: [GC 33919.643: [ParNew: 376030K->102916K(546176K), 0.1462336 secs] 1953320K->1680371K(4642176K), 0.1465861 secs]
    Total time for which application threads were stopped: 0.1557298 seconds
    Application time: 1.3021807 seconds
    34020.827: [GC 34020.827: [ParNew: 376068K->103166K(546176K), 0.3350141 secs] 1953523K->1681429K(4642176K), 0.3353194 secs]
    Total time for which application threads were stopped: 100.0714587 seconds
    Application time: 1.0932169 seconds
    34121.180: [GC 34121.180: [ParNew: 376318K->100333K(546176K), 0.3740967 secs] 1954581K->1680438K(4642176K), 0.3744228 secs]
    Total time for which application threads were stopped: 99.2983213 seconds
    Application time: 0.7258378 seconds
    34122.304: [GC 34122.305: [ParNew: 373485K->115425K(546176K), 0.9584334 secs] 1953590K->1696193K(4642176K), 0.9587701 secs]
    Total time for which application threads were stopped: 0.9823952 seconds
    machine spec and jvm option
    T2000 Solaris10 Sparc
    1cpu 8core 32thread 1GHz, 8GB Memory
    jvm 1.4.2_14
    -d64 -server
    -XX:NewSize=800m -XX:MaxNewSize=800m
    -XX:SurvivorRatio=1
    -XX:+DisableExplicitGC
    -XX:+UseConcMarkSweepGC
    -XX:+UseParNewGC
    -XX:+CMSParallelRemarkEnabled
    -XX:MaxPermSize=256m -XX:PermSize=256m
    -XX:+UsePerfData
    -verbose:gc
    -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
    -XX:+PrintTenuringDistribution
    -XX:+PrintGCApplicationStoppedTime
    -XX:+PrintGCApplicationConcurrentTime
    -Xloggc:/opt/local/jj/jboss/server/fujiyama/log/gc.log
    -Xmx4800M -Xms4800M
    we attempt single thread GC or set 2400M for heap memory
    or -XX:UseParallelGC or set the following param
    -XX:NewSize=1000m -XX:MaxNewSize=1000m
    -XX:SurvivorRatio=6
    -XX:TargetSurvivorRatio=80
    -XX:MaxTenuringThreshold=20
    -Xmx4000M -Xms4000M
    but the situation wasn't improved.

    Hi Thanigaivel
    the above flag reports all the stop the world pauses not only
    those caused because of gc. Unfortunately, this flag has
    misleading name. Thanks for your info!!
    Can you think of any reasons other than GC that cause the stop the world pauses? How can I identify the reason? Are there any VM options to log all the activities that causes the "stop the world" pauses?

  • How can I check if a thread has stopped?

    I'm writing a program which is supposed to open a file, sort all the numbers from smallest to largest value, and then write the sorted list back into a new file. It is specified in the task that I have to use multiple threads, and because of that I have a question:
    I want my program to check if all the threads have stopped before the program starts writing to the output file. Doing it with an if-sentence and/or using a boolean would be perfect, I think. Is there any way I can do this?

    u can use Thread.isAlive() to know if the thread is still running.. else u can use Thread.join() that waits until the Thread excutes till completion..when you would know that the thread is completed

  • "Thread Being Stopped" during break points

    Hello Everyone,
    I read few threads about this topic but couldn't find a solution. So, if anyone has a solution please  help me.
    I am using Visual Basic .NET 2003 and SAP BO 2005 Patch 31.
    I couldn't use breakpoints because I am getting this exception "Thread being Stopped". It is giving me a hard time programming.
    I used to have patch 25 and earlier I could use the breakpoints without any problems. But recently I upgraded it to patch 31. After I upgraded it, I am not able to use the breakpoints because of this error.
    Any advise regarding this problem is welcome.
    Thanking you,
    Yours,
    CK.

    Hi Chanikya!
    i use Microsoft Visual Studio .Net 2003 / SAP B1 2005 A PL 31
    in this case i've made my experience that if you want to step during the break points, there will be problems if you want to access objects from SAPbobsCOM..but if you want to access objects from SAPbouiCOM, there are no problems.
    I don't know how to solve this, but maybe this is your problem too...
    hopeithelps
    Matthias

  • Thread mysteriously stopping.

    I have been developing an application and a perplexing bug keeps arising which I cannot seem to fix due to being unable to replicate it. I have a thread that counts down from a set time interval and upon reaching zero the program refreshes itself. The program is meant to be run continuously and is expected to keep itself updated, but every few days the thread unexpectedly stops while running in the background. Due to the rareness of the situation, I cannot seem to replicate so I can inspect the environment. So I have come here to seek advice on what may be happening, this example is not self contained, as the program is fairly large, but it might spark in idea is someone's mind at what might be happening.
    public class countdownThread extends Thread {
            Thread runner;
            static int threadCount = 0;
            RootFrame parent;
            public int n_timeElapsed = 60;
            public int n_refreshInterval = 60;
            countdownThread(){}
            public countdownThread(RootFrame parent) {
                runner = new Thread(this, "counter");
                this.parent = parent;
                if(threadCount < 1) {
                    threadCount++;
                    start();
            @Override
            public void run() {
                    while(true) {
                        //If more than 0 seconds left
                        while(n_timeElapsed > 0) {
                            n_timeElapsed--;
                            updateTimer(n_timeElapsed);
                            try {
                                sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                        //Reset time to interval after reaching 0
                        n_timeElapsed = n_refreshInterval;
            public void updateTimer(int time) {
                parent.updateAutoRefreshLabel(time);
    }RootPane is a JPanel which contains the method:
    public void updateAutoRefreshLabel(int update){
            statusAutoRefresh.setText("Autorefresh(" + update + ")");
            if(update == 0) {
                //Do update stuff
        }I know you may not be able to help me due to the example situation being self contained, but any suggestions would be much appreciated. I suspect that I am having some concurrency problems, but nothing else is supposed to be interacting with objects the thread is manipulating.
    Thank you,
    Nummsk

    nummsk wrote:
    I have been reading over that tutorial and learned a few things I did not know. I put together and was wondering if I were on the correct track as far as concurrency with Swing goes, I left the countdownThread the same but modified the updateAutoRefreshLabel to the following:
    public void updateAutoRefreshLabel(int update){
    final int localUpdate = update;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    RootFrame.this.statusAutoRefresh.setText("Autorefresh(" + localUpdate + ")");
    if(localUpdate == 0) {
    //Do stuff
    }Am I on the correct track with this direction?
    Edited by: nummsk on Nov 18, 2009 3:56 PMBasically (or not so basic, I suppose), any work done to a GUI component should be done on the EDT. As you now know, whatever you run inside SwingUtilities.invokeLater() is performed on the EDT.
    Doing GUI work from a different Thread can cause rare errors that are super annoying to track down. So if you have to do something from a different Thread (because doing stuff that takes a long time on the EDT is almost as bad as doing GUI work off the EDT), it should basically look like this:
    runningInDifferentThread(){
          invokeLater(someGuiStuff);
          regularMethodCall(); //doesn't do any GUI work, might take a long time
          invokeLater(someOtherGuiStuff);
    }So, yeah, I'd say you're on the right track. Make sure you aren't doing any GUI work off the EDT. The method [SwingUtilities.isEventDispatchThread()|http://java.sun.com/javase/7/docs/api/javax/swing/SwingUtilities.html#isEventDispatchThread%28%29] might be useful for tracking down these cases.
    However, you also want to make sure you aren't putting any non-GUI code that might take a long time to execute onto the EDT.

  • My MacBook Pro won't start after I forced quit because Safari stopped shutdown

    I was deleting items of my external drive through MacBook keeper and when I went to shut down Safari (which was open) stopped the shutdown process. So in the end I force quit the computer. When it came to restarting I get the usula apple symbol and sound when start up begins but there it stops. The spoked wheel just keeps spinning below the Apple Symbol. Can anyone help?

    I have managed to get into my computer through the OS X install disk but now my wi fi hardware is gone. Ie no airport.
    When I try to re install the airport extreme wi fi base station software  it tells me it can't be installed as this version of Mac OS X (Lion) on is volume is not supported.
    Not even an Ethernet cable gets me on line. In system preferences when I do a network diagnostic all I get is the spinning disk. Again, any ideas how to get around this?
    Thanks

  • Problem Getting Thread to Stop

    Hello,
    I am simulating a race. When the winner has been determined, I need to stop the other threads since the race is over. Here is the code that I have with regards to stopping the threads:
    public void simulateTravelTime() {
    try {
    Thread.sleep((int)(Math.random() * distance * 10));
    //Terminate thread execution if the thread is interrupted.
    catch (InterruptedException e) {
    requestStop();
    public void requestStop() {
    stopThread = true;
    public void run() {
    while (!stopThread && (waterInBucket < fullBucket)) {
    //Code to simulate the race and determine if there is a winner.
    //If there's a winner, stop all threads.
    if (winner == true) {
    int n = group.activeCount();
    Thread[] activeThreads = new Thread[n];
    group.enumerate(activeThreads);
    for(int i=0; i<n; i++)
    activeThreads.requestStop();
    //Interrupt the other threads in case they're sleeping.
    group.interrupt();
    It doesn't like the activeThreads[i].requestStop(); line. Anyone know how to alter my code to fix the problem?
    Thx.

    Ahh, I see. Didn't notice that before.
    Okay, I gotta run, but off the top of my head, I think one of the following should work. I prefer the first:
    * When you create the threads, give each one a name that matches it up to your class. Your clas needs to have a name field to match on, or else a separate map maps the name to the Runnable (your class).
    OR
    * Have your class extend Thread.

  • VSTS load test QUESTION : While recording the webPerformanceTest, is it is possible to clear / force to clear cachewithout stopping or closing the IE on recorder?

    VSTS load test QUESTION : While recording the webPerformanceTest, is it is possible to clear / force to clear cache without stopping or closing the IE on recorder?
    I am facing issue, while recording the webtest, our application first time loading any screen calls some requests and 2nd time when browsed the same information if it is available at cache then it will not
    call the requests again.
    How can i force the VSTS to clear cache while recording, so that i can record those requests which gets called at the first time.
    Regards
    SatishK

    Hi SatishK,
    Thanks for your reply.
    >>but my question was while recording (During recording using web test recorder) i want to clear cache.
    Based on your issue,
     I did some research about it,
    but I still find the official document about it. Generally, I know that if we want to clear the web performance test by the
    Cashe Control properties, so I think that it is not possible to clear the cashes when we are recording the web performance.
    If you still want to this feature for web performance test, I suggest you could submit this feature request:
    http://visualstudio.uservoice.com/forums/121579-visual-studio. The Visual Studio product team is listening to user voice there. You
    can send your idea there and people can vote. If you submit this suggestion, I hope you could post that link here, I will help you vote it.
    Thanks for your understanding.
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Long-running Batch eWay JCD - threading and stopping

    I have a requirement to poll for files on a remote server, every few seconds, almost continuously. Furthermore, without making a connections every polling interval. In other words, connect once and stay running, If a file is found, send a JMS message to another service that will process the file, but keep polling for more files. Thus, a long-running service. This will tie up the thread?
    Can I have an array of BatchFTP instances, and in each loop of the long-running process, check each connected instance for incoming files? Or can I only have one instance?
    If the domain is shutdown, will this service shutdown nicely, if it is still in its looping process? If not, I could check another 'command queue' for a shutdown command, but now I have to add code to the domain shutdown script to send that shutdown message to the command queue. Could I instead, somehow check the status of another service in the same project to see if it is shutdown, and therefore know to stop the loop and allow it to be shutdown? I saw an example of a JMX command to check the status of an object. Is that the best way to check the status of a jcd from inside another jcd?
    thanks, Pete

    Hi Chris and thank you,
    I also do not want to build and manage a long-running service, from a performance point of view. The owners of the target server want a file to be picked up as soon as it arrives (within 5 seconds), but they don't want FTP connections created and deleted every 5 seconds. They expect that we will make a connect() call, and then continually loop / poll using dirlist() method.
    When I look at this requirement I also think of re-using it as a generic service - as long as I have a long-running service, I might as well use it for any other long-running, open FTP connections to other servers/userids. So in the same jcd instance, I would connect to multiple FTP servers and execute a loop where I go through a list of FTP connections, and for each, I would go through a list of folders that should be polled (using dirlist method). So I only have one JCD running for a long time but it could have multiple FTP connections open. That is why I am thinking of using an array of BatchFTP objects.
    When your code shows a Scheduler eWay input, do you mean that the JCD will triggered by the first Scheduler message, but would then go into a loop, doing work, and performing a JMS.receive on that Scheduler queue for the 2dn, 3rd, .. nth Scheduler message? So because the jcd is still running, it still had all its objects and FTP connections (open), but its looping is controlled by the Scheduler message?
    I'm running 513u3. I am worried about shutdown. I think it might not listen to a shutdown command. So that is why I was thinking about putting in some code at the bottom of the loop that would check, somehow, if a shutdown is in progress.
    Peter

  • Force wait activity to stop and continue flow

    Dear,
    Is it possible to force an active wait activity (that is scheduled to expire a couple of hours later) to stop and to continue the flow with the next activity?
    Thanks in advance for your feedback,
    Veerle Antonissen

    How would you like to force the wait activity prematurely? AFAIK this is only possible with by setting an alarm on a reveive activity, i.e. waiting for a maximum time (comparable to wait) and at the same time waiting for a message (receive activity), whatever happens first. If you send a message to the receive, it will continue before the alarm times out.
    Does this solve your problem?

  • Thread IMMEDIATE stopping

    Hi,
    Here's my problem : I'm building a Command station that has to be able to start an execution Thread and also to stop it immediately (a.k.a PANIC BUTTON) No problem with starting the Thread, but the problem is with the stopping. The thread i'm starting achieves native calls on an embedded system with the use of JNI, so I can't implement changes directly in the native code to respond to interrupts.
    I have to specify that the run( ) method of my Thread does NOT contain a while statement, in fact there is only ONE CALL, for example :
    public void run( ) { embedded_system.flashLEDForAnHour(); }
    So if anyone has an idea about a solution or a hint for a solution, I would be very grateful because I've been searching for days!
    greetings,
    Peter

    A solution to what? If you have to specify that,
    specify it. Write it in your API documents. But I
    don't see why you would have to specify such a thing,
    or even what would be the point of specifying it.
    After all, that flashLEDForAnHour method could contain
    any code at all, couldn't it? Including
    while-statements?
    What about for-statements? Are they allowed? Because
    any while-statement can be rewritten as a
    for-statement.I think he just means his actual thread is just invoking a long-running method which he can't change (3rd-party method). There's not a real solution to this problem. If the long-running method has no "get outta here now" technique, you're stuck with calling thread.stop(), which is of course an abnormal thread termination (and hence why it's deprecated) as it will/may not properly clean up, just like abnormally killing a long-running app.

  • May threads force other threads to sleep?!

    Hi all,
    Really hope someone may help me!! I have four classes. The master program, class A, calls class B (not a thread) when an action occurs. The actions effect the behaviour of the third class ObjectThread. B may sometime force the ObjectThread thread to sleep for some time (not predetermined). Then when it's time, B awakens ObjectThread, which continues.
    The problem is that I don't want B to lock while an ObjectThread is sleeping. Hence I have created class C (also a thread), which is called only when ObjectThread needs to sleep. Input to C is a handle to the respective ObjectThread. But I can't get class C to force ObjectThread to sleep! I've tried not having C as a thread, but merely as a simple class, then it works but the whole thing locks.
    How can I make the C thread perform first:
    handleToObjectThread.sleep (); (this I guess may be managed with while loops)
    then whenever I feel like it in the B class
    handleToObjectThread.interrupt ();
    Please help!!
    / jez

    i assume that ObjectThread has a loop in its run() method...
    why not at the start or end of the loop, get it to check to see if it should be sleeping
    then class B could just set a flag (boolean) or an int (time to sleep) in ObjectThread
    so..
    ObjectThread extends Thread{
    private boolean sleep=false;
    public void run(){
      while(doit){
       if(sleep){
        try{
         while(!sleep){
          Thread.sleep(whatever);
        catch(InterruptedException ie){};
       //rest of loop
    public void goToSleep(){
      sleep=true;
    public void wakeUp(){
      sleep=false;
    interrupt(); // only if you need to wake immediately
    }

  • Thread wont stop

    Hello
    I have an applet that uses two threads to print out things in a JTextArea.It print fine but when trying to stop the thread whit a flag (boolean) it seems to assume that the flag always is true. What have I missed or forgotten to do ? Submitting the code of the two classes I use.
    //From the applet class
       knapp1=new JButton("Aktivera utskrift fr�n tr�d 1 ");
       knapp1.addActionListener(new KnappLyssnare1());
       public class KnappLyssnare1 implements ActionListener{
          public void actionPerformed(ActionEvent e){
         oneNumberClicked++;
         Trad1 tr�d1=new Trad1(area);     
         if (ok==false){
            knapp1.setText("Deaktivera tr�d 1");
            ok=true;
            tr�d1.start();
         else{
            knapp1.setText("Aktivera tr�d 1");
            ok=false;
            System.out.println("�r i else ok==false;");
            tr�d1.setFlagga1(ok);
    //From the Thread class
    private boolean bol=true;
      public void run(){         
          do{
          arean.append("Utskrift fr�n tr�d 1\n ");
          try{
             Thread.sleep(1000);
          }catch(InterruptedException ire){
             System.out.println("Tr�den avbr�ts");
          }while(bol==true) ;
    public void setFlagga1(boolean ok)
          this.bol=ok;
          System.out.println("�r i setFlagga");
    }Greatful for help !

    You probably already found it:
    Trad1 tr�d1=new Trad1(area);should be done outside the listener, only once (if one thread).

  • Thread that stopped responding

    Hi All,
    I have a problem i don't know how to solve - i have a server written in NIO that accepts connections in one thread and do other stuff in other threads.
    After about 2.5 day, the thread accepting the connections stopped responding without giving me any warning - i tried to connect and i can't (i don't receive even an ack), and when i use a profiler i don't see the thread there. But the port on which it listens is still busy (i see that in netstat).
    The run method is surrounded by try-catch so i thought that i'll see if the thread dies - even in throwable, yet i don't see anything in the log.
    public void run()
            openServerSocket();
            while (true)
                try
                    serveConnection(); // The select and handling
                catch (Throwable t)
                    log.log(Level.SEVERE, "Problem serving connections: ", t);
        }What can i check next? How should i approach this problem?
    Kind regards,
    Snayit

    Haven't you got log-files of your long-running process? If not I guess, you've learnt something now.
    If it's a global resource that was depeleted you might find something in /var/log/* (especially messages, maybe syslog).
    If all that fails start up a debugger and attach to the process if possible to see where it hangs.

  • Threads and stop()

    Hi
    I am struggling with the deprecated stop() method.I have a requirement in which I have to stop the thread from whatever it is doing after X amount of time.I cant go the interrupt route as my code doesnt satisfy any conditions for the interrupt to work (For Ex. sleep() and wait() ; running in a loop ; etc).
    Stop method seems ideal to me ; as it does the work I want ; but cant use it as its not a good programming practice.
    Assigning Thread to null also doesnt work.
    Any ideas.
    Thanks
    Pankaj

    Hope this helps
    The proper way to stop a running thread is to set a variable that the thread checks occasionally. When the thread detects that the variable is set, it should return from the run() method.
    Note: Thread.suspend() and Thread.stop() provide asynchronous methods of stopping a thread. However, these methods have been deprecated because they are very unsafe. Using them often results in deadlocks and incorrect resource cleanup.
        // Create and start the thread
        MyThread thread = new MyThread();
        thread.start();
        // Do work...
        // Stop the thread
        thread.allDone = true;
        class MyThread extends Thread {
            boolean allDone = false;
            // This method is called when the thread runs
            public void run() {
                while (true) {
                    // Do work...
                    if (allDone) {
                        return;
                    // Do work...
    Alternatively declare a stop() method inside your thread or runnable class and call this method to set allDone variable to false.

Maybe you are looking for