Catch/Prevent System.exit call in other thread

Wasn't sure where to put this so apologies if this is in the wrong section.
I have an application that runs a particular method contained in a JAR that is written/provided by somebody else (they implement an interface I provide). They have complete free range as to what their application does. I then run this application in a separate thread, the idea being that when it completes my original application is still running.
What I have provided so far is ok PROVIDED that the given JAR does not perform a System.exit call which is very possible. I want to prevent them from doing this but I don't want to contacting the author asking them to remove all invokations of System.exit.
I found this article: https://www.securecoding.cert.org/confluence/display/java/EXC04-J.+Prevent+against+inadvertent+calls+to+System.exit%28%29+or+forced+shutdown and so I tried to create my own SecurityManager. Unfortunately though despite explicitly putting the running of the applicaiton in a catch block for AccessControlException it doesn't catch it and fails. Does anybody have an idea of how to overcome this.
In summary: how can I prevent a call to System.exit being invoked (or when it is invoked, catch it and prevent it from actually happening) inside another thread?

batterj2 wrote:
I was unable to do any File I/O afterwards which seems strange as its extending the original SecurityManager so I thought it wouldn't have any difference.No, that code isn't "extending the original SecurityManager". It's creating a SecurityManager which overrides some SecurityManager which may or may not be the same as the actual SecurityManager which was in place when you applied it. From what you say, it's not the same.
Remember you don't extend objects, you extend classes.
You could write something which gets a link to the current security manager, then delegates all calls to that security manager except the ones you don't want to delegate.

Similar Messages

  • Trapping System.exit() calls

    Hey folks. I'm wondering if anyone has a best practice for trapping System.exit() calls in managed applications that are running in a a single MBeanServer. In our design, there is a single VM that runs the MBeanServer and any loaded applications. If any loaded application (MBean) uses a System.exit() call, this will bring down the entire agent. We've put some preventative code into a custom SecurityManger to at least catch the exit call and automatically restart the agent, but I'm figuring there is a better way to do this.
    We're making it a best practice to NOT use System.exit() in any JMX-managed applications that will run inside our agent and rather use Thread termination code. Has anyone run into these same issues? If you look at the JMX Server example in the Sun JMX tutorial, if I throw a System.exit() call into one of the sample MBeans, the server will die.
    As I was perusing a local bookstore, I thumbed through a JMX book that had some example code in it, and in their "Server" example code, they have a shutdown and a startup method. In the shutdown method there is a System.exit() call, which, in my understanding, will bring down the agent. How, then, could you call startup() on an agent that isn't running?
    Are these designs assuming that the MBean server is running under J2EE application server like WebLogic or WebSphere?
    Any thoughts would be much appreciated. Thanks.
    -Phil

    the int you pass to System.exit is returned by the JVM...... (I think, I forget........)
    Generally use 0 to signify "normal" exit
    Generally use 1 to signify an "abnormal" exit (so you terminated the program (using exit) becuase you couldn't handle the exception nicely)
    So you can use the return value to "monitor" your program...... it's an old concept, C programmers use it all the time....

  • Prevent System.exit(0)

    Hi Everybody!
    I have the following problem.
    I am developing an web-application running on a Tomcat server.
    Furthermore I am using some additional libraries, from which I only have the class-files. Nevertheless I decompiled them and found, that one method calls a System.exit(0) in its catch block, and this is horrible, because the server always shuts down in case of failure.
    What shall i do to prevent this? Altering the library will not be possible. Any ideas?
    I created a small example to point out my problem:
    public class Testing {
         private void methodA(String s) {
              try {
                   int i = Integer.parseInt(s);
                   System.out.println("Value of i: " +i);
                   Thread.sleep(1000);
              catch (Exception e) {
                   e.printStackTrace();
                   System.exit(0);
         }     //methodA
         public static void main(String[] args) {
              Testing t = new Testing();
              for (int i = 0; i < 10; i++) {
                   if (i == 5)
                        t.methodA("a");
                   else
                        t.methodA(String.valueOf(i));
              }     //for
    }Just think of methodA() as an method that can not be altered... How can I force the for-loop to continue when methodA() fails?
    (This is not my actual problem, but it points out my problem... ;)
    Thanks in Advance!
    Stef

    I was able to solve the problem by using the following code :-
    final SecurityManager securityManager = new SecurityManager()
         public void checkPermission(Permission permission)
              //This Prevents the shutting down of JVM.(in case of System.exit())
         if ("exitVM".equals(permission.getName()))
         throw new SecurityException("System.exit attempted and blocked.");
    System.setSecurityManager(securityManager);
    Hope it helps some one ..................... ;)

  • Preventing System.exit()

    I've written a class loader that executes .jar files across a network from a central application. Works great - except when one of those jar files calls a System.exit().
    Since the purpose of this application is to have several applications "executing" across a network, having one of them call System.exit() kills all of them. Are there any methods of scanning the class files as they are being loaded and having code replaced? For example, searching for System.exit(someInt) or even JFrame.EXIT_ON_CLOSE and then replacing this bytecode with some more acceptable bytecode that instructs the parent program the child wishes to terminate?
    Rewriting all of the programs to be loaded so that they don't call System.exit() or its variations isn't an option here, so I'm open to any suggestions.

    BTW: Overriding system libraries is against
    standards, but does work.
    http://java.sun.com/j2se/1.4.2/docs/guide/standards/
    In java.lang.Runtime
    public void exit(int status) {
    throw new Error("Exit called with
    led with status="+status);
    }Create a jar and copy it to <java_home>/lib/endorsed
    The run the following
    public class Main {
    public static void main(String[] args) {
    System.exit(1);
    }And you will get the follow when run with this
    "modified" JRE
    "C:\Program Files\Java\jre1.6.0\bin"\java -cp .Main
    Exception in thread "main" java.lang.Error: Exit
    called with status=1
    at java.lang.Runtime.exit(Runtime.java:86)
    at java.lang.System.exit(Unknown Source)
    at Main.main(Main.java:11)
    Yes, but then it works only on your machine.

  • Calling System.exit() from multiple threads

    Hi,
    Why would calling System.exit() from multiple threads cause all the threads to block?
    Laith

    Thanks for your replies.
    I made further tests and the problem is actually not as I described it first.
    I'm using a shutdown hook that would stop all running threads if the program is stopped externally (using ctl-c for example) (I'm not using Thread.stop(), but setting a boolean value to false that would make the thread exit a while() loop in run()) .
    One of the running threads would call System.exit(-1) just before it would exit run().
    This thread is getting blocked if it is stopped by the shutdown hook.
    I know that this is a bad coding practice, bout would still appreciate an explanation to the reason why the thread is actually blocked by System.exit().
    Laith

  • System.exit() didn't kill all the threads it spawned in Linux

    Facing problem while doing System.exit(0);
    Even though it is happening inconsistently but this how it is-------.
    The main application has spawned some threads.
    On receiving a particular event it interrupts all the threads and calls system.exit(0).
    Each thread after catching interrupted exception sends a interrupt to itself.
    What I'm observing is, once in a while the spwned threads are still hanging even though the application has exited.
    I'm having
    1) java version "1.4.2_04" and
    2) Linux 2.4.21-27.EL

    After writing Java code for 6 or 7 years, then having a years break and writing C++
    and D code. I came back to Java and am having the same problem as you.
    The cause of my problem was that I was writing the wrong code lol I was
    trying to use an ActionEvent instead of a WindowEvent ie:
    Im on Slackware btw. (nothing but the best )
    PS. I have also noticed that MPlayer does the same thing when you close it down.
    you can see it in the System processes still running. I havent looked at their
    code though.

  • How to "kill" AWT Event Queue thread without using System.exit()?

    When I run my program and the first GUI window is displayed a new thread is created - "AWT-Event Queue". When my program finishes, this thread stays alive and I think it causes some problems I have experienced lately.
    Is there any possibility to "kill" this thread without using System.exit() (I can't use it for some specific reasons)

    All threads are kept alive by the JVM session. When you use System.exit(int) you kill the current session, thus killing all threads. I'm not sure, though...
    What you could do, to make sure all threads die, is to make ever thread you start member of a thread group. When you want to exit you app, you kill all the threads in the thread group before exit.
    A small example:
    //Should be declared somewhere
    static ThreadGroup threadGroup = new ThreadGroup("My ThreadGroup");
    class MyClass extends Thread {
    super(threadGroup, "MyThread");
    Thread thread = new Thread(threadGroup, "MySecondThread");
    void exit() {
    //Deprecated, seek alternative
    threadGroup.stop();
    System.exit(0);
    }

  • How stop call to System.exit but allow them to install Securitymanager?

    I have an application that allows you to start a java application from inside it (it then gives you monitoring capabilities). I want this to work with pretty much any desktop application, even those that require their own security manager. However, i don't want their application to be able to shutdown the jvm. How can I do this?
    As far as I can tell, there's no way to allow them to add the securitymanager, "wrapped" by mine is there?
    And I thought of using AccessController.doPriviledgedAction(...) and giving them a context where they can add a security manager but not call system.exit, but then if they do add a security manager, won't it have the final say on system.exit calls?
    Is there a solution here?

    6tr6tr wrote:
    Thanks for the reply!
    Hmmm, the problem with that is I need the users to be able to use my application without access to that app's source code. So they need to be able to run that program (as 3rd party black-boxed code) inside my app and still have this work properly. Is there another way?
    Source code?
    You don't need any source code for what I suggested.
    If a frame/jframe tries to exit on close, I can grab and stop that. my problem is if some random code tries to call system.exit(). Is there any other way to intercept it?
    UPDATE: the only solution i could come up with is to use bytecode engineering + classloading.
    Which I doubt will help if they call it with reflection.
    You could use the bootstrap command line options and replace System with your own version. Add some functionality to how it sets up the security manager and/or make System.exit() do nothing, but provide another name for yourself.

  • System.exit(o) in Swing

    Hi,
    In my Swing application, as soon as I start the main() method, a dialog containing Username and Password fields with OK and Cancel buttons gets popped-up. I have a propertyChangeListener which gets notified when Ok or cancel is pressed and when Cancel is pressed, System.exit(0) is called to exit the JVM.
    So, there are two threads running -
    One - the main thread which invokes the dialog pop-up
    Second - the propertychangelistener which calls the System.exit(0) on pressing Cancel button.
    So, at times, after pressing cancel button, the application does not exit but invokes the previously running thread (main thread). But this does not happen always.
    Could you please let me know why the application does not terminate completely and how to resolve this?
    Thanks in advance!

    Hi,
    As I had already mentioned in my previous post -
    Here is the pseudo-code which fails to terminate on pressing Cancel button at times.
    ================The Login dialog code=============
    public LoginDialog()
    // Other code
    JOptionPane optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
    optionPane.addPropertyChangeListener(new PropertyChangeListener()
    public void propertyChange(PropertyChangeEvent e)
              Object value = optionPane.getValue();
              if (value.equals(YES))
              else
    // user closed dialog or clicked cancel
    setVisible(false);
    System.exit(0);
    ===============The main thread===================
    This main() method calls the logindialog with username and passwrd as parameters.
    So, initially, the main() thread is started and the login dialog is displayed. On pressing Cancel in this dialog, the control goes to propertyChangeListener of the loginDialog() and calls System.exit(0) which should terminate the entire application, but at times, the previously running main thread is resumed and the application is not terminated.
    Please clarify why this happens.
    Thanks in advance!!
    });

  • Finally and System.exit()-Will work togother?

    Does finally block execute if we call System.exit() inside a try block?
    try{
    if(condition)System.exit(0);
    finally{
    System.out.println("Inside finally");
    If condition is true, will finally execute?
    When i tried it on jdk1.3, it's not executed.

    I'm pretty sure the finally{} block will never be executed. When calling System.exit(), it tells the application to terminate immediately. Here's something you could try, if you have code that needs to run if there's been an exception or not. Sorry for the horrible code conventions.
    boolean sysExit = false;
    try{
    if(condition){
    sysExit = true;
    catch(Exception e){
    //Do whatever.
    finally{
    //Do finally stuff
    if(sysExit) System.exit(status);
    }

  • Capture System.exit

    Hello
    I am writing a program where I need to use utilities from a separate jar file. The only public entry point is that jar file's main method and it ends with System.exit
    Is there a way to capture the System.exit call so my program doesn't terminate?
    If so, can I capture the return value?
    Using Runtime.exec() is not preferred as it limits the number of command line parameters supplied to the called program.
    I'd appreciate any suggestions on how do do this or sugggestions on where to look for further information.
    aqd

    how could you expect me to use JAVA command without compiling it with Javac??
    I complied the java code using javac and then called(executed ) it using the Java..
    I am using JNI_Create/JavaVM() to create a JVM from CPP file. that works fine. Now, my issue is that I want to capture a couple of exit codes that are returned from the System.exit() of the java code.
    now, guys.. is there any way to capture that exit codes returning by Ssytem.exit() in or using JNI ??
    if yes, please help me with the code snippets.
    Thanks,
    Soujanya.R

  • System.exit(1)

    I use NetBean6.5 , Creme, window mobile 6, to create simple program for learning. I add a button with the System.exit to close out the program. The program closes successfuly but it gives me this error on netBean output:
    java.lang.NullPointerException
    at org.netbeans.modules.j2me.cdc.project.nsicom.NSIcomExecDeployTask.execute(NSIcomExecDeployTask.java:267)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at sun.reflect.GeneratedMethodAccessor80.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:357)
    at org.apache.tools.ant.Target.performTasks(Target.java:385)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:273)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:499)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
    BUILD FAILED (total time: 15 seconds)
    Does anyone know why?

    nevermind just found the solution. Don't use System.exit(1), but use System.exit(0);

  • Close using system.exit()

    could anyone tell me to write a new program which has a button labelled 'close'. when click on 'close', it should terminate the addition program.
    import javabook.*;
    class addition
         public static void main(String args[])
              int a, b,c;
              MainWindow mainWindow = new MainWindow(); // creates a frame,mainwindow is in javabook package
              InputBox inputBox = new InputBox(mainWindow); // creates an inputbox, is in javabook package
              OutputBox outputBox = new OutputBox(mainWindow);// creates an outputbox;
              outputBox.setVisible(true);
              a= inputBox.getInteger("Enter an integer: ");
              b=inputBox.getInteger("Enter and integer: ");
              c= a + b;
              outputBox.printLine("C = %d\n",c);
    }

    closeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
    });

  • Denying Thread calling System.exit() successfully

    Hi all,
    i start another java app from within my code by calling it's main()-method in an own thread.
    As i don't have any access to the code of the java app i can't prevent it from calling System.exit() when the corresponding window is closed.
    How can i prevent the "threaded" java app from also closing my wrapping application when it is finished?
    Greetings,
    Bernhard

    You can install a security manager (your own) in your application and override the method checkExit(int status) in order to handle the event:
    class OwnSecurityManager extends SecurityManager{
         public void checkExit(int code){
              if(code == 1){
                   super.checkExit(code);
                   throw new SecurityException("Not allowed here"); //or your handling code
              }else{
              //other codes
    //in your app you install the manager like this
    SecurityManager s = new OwnManager();
    System.setSecurityManager(s);

  • The ABAP call stack was: SYSTEM-EXIT of program BBPGLOBAL

    Hi
    We are using SRM 5.0. We are facing a strange problem. We are able to see the initial screen of SRM EBP in the browser. But once the user name and password are provided the system goes for a dump with the following error:
    The following error text was processed in the system SS0 : System error
    The error occurred on the application server <Server Name> and in the work process 0 .
    The termination type was: ABORT_MESSAGE_STATE
    The ABAP call stack was: SYSTEM-EXIT of program BBPGLOBAL
    <b>SM21 Log:</b>
    Short Text
         Transaction Canceled &9&9&5 ( &a &b &c &d &e &f &g &h &i )
         The transaction has been terminated.  This may be caused by a
         termination message from the application (MESSAGE Axxx) or by an error
         detected by the SAP System due to which it makes no sense to proceed
         with the transaction.  The actual reason for the termination is
         indicated by the T100 message and the parameters.
    Transaction Canceled ITS_P 001 ( )
    Message Id: ITS_P
    Message No: 001
    I just checked these threads but did not help much,
    RABAX_STATE  error after loggin into BBPSTART service in SRM 4.
    ITS_TEMPLATE_NOT_FOUND error
    Besides I tried this note: 790727 as well, still I get the same error.
    Any help would be highly appreciated.
    Thanks in advance
    Kathirvel Balakrishnan

    Hi
    <u>Please do the following steps.</u>
    <b>When you are using the Internal ITS,you need not run the report W3_PUBLISH_SERVICES.(only SIAC_PUBLISH_ALL_INT )
    ALso pls check the foll:
    -->activate the services through SICF tcode.
    > Go to SICF transaction and activate the whole tree under the node Default host>sap>bc>gui>sap>its.
    >Also maintain the settings in SE80>utilities>settings>internet transaction server-->test service/Publish. (BBPSTART , BBPGLOBAL etc)
    Table TWPURLSVR should have entries for the / SRM server line as well as gui and web server.
    Could you please review again the following steps ?
    Did you check that ICM was working correctly (Transaction -  SMICM) ?
    1-Activate the necessary ICF services
    With transaction SICF and locate the
    services by path
    /sap/public/bc/its/mimes
    /sap/bc/gui/sap/its/webgui
    2- Publish the IAC Services
    With Transaction SE80 locate from
    the menu Utilities -> Settings ->
    Internet Transaction Server (Tab) ->
    Publish (Tab) and set “On Selected
    Site” = INTERNAL.
    3- Locate the Internet Services SYSTEM and WEBGUI.
    Publish these services with the Context
    Menu -> Publish -> Complete Service
    4- Browse to http://<server>:<icmport>/sap/bc/gui/
    sap/its/webgui/! and login to the
    webgui.</b>
    Hope this will help.
    Please reward suitable points.
    Regards
    - Atul

Maybe you are looking for

  • Why do I get this error when executing this javascript?

    == Issue == I have another kind of problem with Firefox == Description == <code>var firefoxWindow = getWindows()[0]; var browser = firefoxWindow.getBrowser(); var doc = browser.contentDocument; var elem = null; var elems = doc.getElementsByTagName('t

  • Error while streaming from ipad mini to apple tv

    While using my ipad mini to stream through airplay mirroring on apple tv (3rd generation) when I switch to full screen view the stream stops and I get an error message saying an "an error occurred loading this content" How do I correc this? Happens e

  • Developer surface Unit troubleshooting

    I recently aquired a Surface 1.0 Developer unit. The bulb does not work, however I have replaced it with a brand new bulb and same thing, bulb not lighting. Unit will go through startup and can hear the windows Vista startup sound but obviously nothi

  • Program monitor freezing

    Hi, I just switched over to premiere CC and have been having trouble with the program monitor freezing up. I am editing R3D files 5k and therefore have the playback quality set to 1/8. But every time I'm trying to scale up the picture, the monitor fr

  • Phone is stuck in emergency mode?

    phone is stuck in emergency mode?