Can I intercept "System.exit" in a spawned GUI thread?

I am writing a large GUI application that optionally spawns other GUI threads. These spawned threads are special-purpose text editors. It is important that the editor knows when it is about to be closed, so that it can prompt the user to save a modified file.
The editors are based upon javax.swing.JFrame, and I have overridden the "windowClosing" method of a WindowAdapter to check file status and prompt when necessary. This method performs as desired when I close the editor window manually. However, when I close the main application (which calls System.exit(0) ), the editor frames also close without any invocation of my windowClosing method.
Is there any way the dependent editor JFrame can be alerted that the virtual machine is about to be ended? I could probably keep a list in my main application of all the dependent processes that need to be cleanly ended, but it would be much simpler (and so much more object-oriented) if the dependent thread could take care of itself!

I was not aware of the Frame.getFrames() method; this is apparently good enough to find all the dependent windows I have created. Thanks for pointing this out.
As to the spawned threads, perhaps you could comment on my method. I was actually hoping to open the editors as independent applications that would persist after the main GUI was closed. To do this, I gave my editor class an associated static Runnable, like so:
   public static class Starter extends Thread {
         String[] arguments = new String[0];
         public void run() {
            MyEditor re = new MyEditor();
            if( arguments.length > 0) re.setFileName(arguments[0]);
            re.setVisible(true);
         public void copyArguments( String[] args) {
            arguments = Arrays.copyOf(args, args.length);
   }which I invoked from my main GUI in the following code:
   Starter starter = new Starter();
   String[] startArgs = {"myfilename.txt", "more parameters"};
   starter.copyArguments(startArgs);
   starter.setDaemon(false);
   starter.start();This does indeed start the editor, but it is in the same virtual machine, since the editor stops when the GUI stops. Is this method setting me up for trouble? Is there a way to do what I originally wanted, starting the editor in a new virtual machine?

Similar Messages

  • How can I  get System dates  with time scheduler using threads

    how can I get System dates with time scheduler using threads.is there any idea to update Date in my application along with system Date automatic updation...

    What the heck are you talking about and whatr has it to do with threads?
    Current time: System.currentTimeMillis. Date instances are not supposed to be updated.

  • How to intercept "System.exit"?

    I am writing a large GUI application that optionally spawns other GUI threads. These spawned threads are special-purpose text editors. It is important that the editor knows when it is about to be closed, so that it can prompt the user to save a modified file.
    The editors are based upon javax.swing.JFrame, and I have overridden the "windowClosing" method of a WindowAdapter to check file status and prompt when necessary. This method performs as desired when I close the editor window manually. However, when I close the main application (which calls System.exit(0) ), the editor frames also close without any invocation of my windowClosing method.
    Is there any way the dependent editor JFrame can be alerted that the virtual machine is about to be ended? I could probably keep a list in my main application of all the dependent processes that need to be cleanly ended, but it would be much simpler (and so much more object-oriented) if the dependent thread could take care of itself!

    MarkHausman wrote:
    As you suggested, I posted this question on the Swing forum.
    For those who are interested: the Swing solution I was offered was to make use of the static function Frame.getFrames(). This allows access to all frames launched by an application. By putting this call in my main shutdown method, I can identify all spawned editor frames and call each one's shutdown method.
    This is not as satisfying as my original desire, to have the spawned frame recognize when the VM is about to close, but it is easy enough to implement that I am going with it.And why wouldn't addShutdownHook() work?

  • Intercepting System.exit() and System.out.println() calls

    hi there,
    I have often problems when working with code that uses System.exit() and System.out.println() extensively, because it becomes difficult to debug.
    Basically I do have wrappers for System.exit() (my own static exit function) and for System.out.println() (log4j).
    Still not all programmers are using these methods; Probably the only way to enforce this is some kind of code warrior, but I was hoping to be able to intercept the two System.XXX calls (and throw an appropriate Exception). is this possible ??

    Why not simply make your own security manager andhandle checkExit() and checkWrite?
    Does anyone have a simple example of this? Please?System.exit() can be intercepted using a security manager, but not System.out.xxx.
    Here is a short example:
    //set your security manager
    static{
         SecurityManager s = new OwnSecurityManager();
         System.setSecurityManager(s);
    //redirect the out stream
    try{
         PrintStream ps = new PrintStream(new FileOutputStream("output.txt"));
         System.setOut(ps);
    }catch(IOException ioe){
         ioe.printStackTrace();
    //some tests
    System.out.println("Test");
    System.exit(2);
    //your security manager
    class OwnSecurityManager extends SecurityManager{
         public void checkExit(int code){
           if(code > 0){
             super.checkExit(code);
             throw new SecurityException("Not allowed here->" + code);
         public void checkRead(FileDescriptor fd){
         public void checkRead(String file){
         public void checkRead(String file, Object context){
         public void checkPermission(Permission perm){
           if(perm.getName().equals("exitVM")){
             System.out.println("exitVM");
    }

  • How do I exit a java program based on condition can i use system.exit

    I have java program that is called by another program that I dont have control on. My program returns a bigdecimal... but if the ordernumber is empty in my program i dont wnat to do anything.. does system.exit work in that condition... i put it int he else if ordernumber is empty condition.. but i dont think that is the right approach..

    When software module is expected to bring some result, it should bring the result, positive or negative. I think you should check what your counterpart software expects as positive or negative result. And then implement your software this way. You can use System.exit, but this call is employed usually to indicate status with the software after it's completion and not to return any resulting value.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#exit(int)

  • System.exit(0) closes wrong window

    I use a web browser to display an applet.
    In the applet I have the possibility to start a new webbrowser window with myapplet.getAppletContext().showDocument(url, "_blank");In the new webpage I also start a new applet.
    To close this new web page I call System.exit(0); from the applet in the new page.
    The strang thing that happens than is that the parent window is closed and the newly opened web page is still active.
    If I open these windows myself in the browser, I can close them from the applet.
    Can anybody help.

    System.exit is not permitted by an applet for the above mentioned reason.
    Multiple browser windows with applets share the same jvm so exiting the
    jvm makes the other applets crash.
    When you give the applet permission (sign or policy) system.exit will crash
    the browser.
    It is possible to close a popup window, since I don't beleve in the JSObject
    anymore (crashed too many times with too many bugs in mozilla).
    You can use another way, here it is.
    in your applet// to open the window
    this.getAppletContext().showDocument(
         new URL("javascript: myPopupWindow = window.open('yourPage.htm');myPopupWindow.focus()"));
    // to close the window
    this.getAppletContext().showDocument(
         new URL("javascript: myPopupWindow.close()"));in your html page:<script>
    var myPopupWindow = null;
    </script>

  • System.exit(0) problem

    Hi there,
    I open C++ GUI application from Java (using JNI native call). When user clicks "x" and closes GUI application, I'd like to shutdown JVM also. In my code, when user clicks "x", C++ side calls Java method (that contains System.exit(0) call) and this results in the java.exe - Application Error: "The instruction at 0x0 referenced at 0x0. The memory couldn't be read".
    I use Jace to handle JNI calls but this sounds like a pure JNI problem.
    Many thanks in advance.
    Kalle.

    System.exit(0)kills the main thread but you still is in the native function. Return has no a valid address. CallSystem.exit(0) only from JAVA code.

  • Spawning another java process after System.exit(0);

    Hi everyone
    I have an application that Im trying to test. Unfortunately one of these tests requires me to spawn another java process after a System.exit(0); has executed. Since this exits the VM its proving very difficult. Does anyone know of a way to restart the VM after the System.exit has run?
    Thanks

    Hi everyone
    I have an application that Im trying to test.
    Unfortunately one of these tests requires me to spawn
    another java process after a System.exit(0); has
    executed. Since this exits the VM its proving very
    difficult. Does anyone know of a way to restart the VM
    after the System.exit has run?Exactly what do you want to do?
    If the application is supposed to only have one exit point then add a security manager and disallow all the other exit points. Then you can use Runtime.exec() to start the second application just before the real exit point.
    However note that if there are other calls to System.exit in the application then it is very likely that this will cause some unexpected failures in terms of security exceptions.
    You could also use Runtime.addShutdownHook() which would run your second app. The hook would be called as the application exits.
    You might want to consider what happens if someone just kills the application (say with 'kill -9' or the windows task manager.) In either of those cases there is nothing that you can do in java to make that second application run.
    You might also want to consider why you are doing this in the first place. As suggested a script solution is probably a better solution.

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

  • Can't find user exit or enhancement at RGJVBR15

    Hi everyone,
    I need your help guys. Right now,i'm developed sapscript for billing statement (cash call and expenditure). I have finished the form but i have problem at print program RGJVBR15. This print program is called by RGJVBR10 (Tcode : GJ14 --> Hard Copy Billing).GJ 12 and GJ 13 is used to extract data that will be used by forms.
    There is statement like this in RGJVBR15 at subroutine CREATE_EXPENDITURE (Line 1421 in include file RGJBF_I1) :
    AT NEW C5_CURR. --> Group by funding currency
       PERFORM POPULATE_SPOOL_ID
    ENDAT.
      PERFORM F6100_PROC_...  -> This will be used to open form,write form (sapscript)
    AT END OF C5_CURR.
    ENDAT.
    The problem is that i want to change this logic. I want to change the standard logic (display report group by funding currency), i want to ignore this and instead using group currency. So there only one report produced with one currency only (if using standard logic there is more than 1 report based on funding currency). But i can't find user exit or enhancement in this SAP Standard Program. Is anyone know if there is user exit or enhancement in this program? I don't want to use implicit enhancement because it's will produce problem when client want to upgrade their system. Thank you.
    Best Regards,
    Satria

    hi,
    for tcode GJ14 user exits avaliables are
    Exit Name           Description
    JVA-IM-1             Joint Venture: Integration Manager Set Intercompany Lines
    JVA_IM_2            User Exit Splitting
    JVA_IM_3            User Exit Check Document
    regards,
    paras

  • Denying system.exit in java code

    My objective is to nullifying the system.exit programmed. By goggling i learn t that this can be done by adding permission in policy file. But as far my google search i dont understand how to deny a permission. Most of them says about granting a permission. Can anyone clarify how to deny a permission.
    Steps i tried.
    Sample program: which does nothing other than calling system.exit(0) as the first line in main method.
    added the following line to java.policy file in my JAVA_HOME/jre/lib/security
    grant {
              permission java.lang.RuntimePermission "exitVM";
    Also tried adding only
    permission java.lang.RuntimePermission "exitVM";
    to the already available grant block.
    Also commented out
    //grant codeBase "file:${java.home}/lib/ext/*" {
    //     permission java.security.AllPermission;
    After that i understood that the default java policy file is java.home\lib\security\java.policy. So made all the change above mentioned there too.
    But i could not achieve it. Can any one help me on this.
    Win 2000/ Java1.4.2_12/no command line arguments while running the program.

    Welcome to the Forums.
    Please go through the FAQ of the Forum.
    You has posted your query in the wrong Forum, this one is dedicated to Oracle Forms.
    Please try {forum:id=1050}.
    Regards,

  • Can't open system preferences in macbook pro OS X v10.6.8

    Can't open system preferences. Says it may be damaged or incomplete.

    Thank you for answer.
    I can't use or create a guest account, 'cause it's in system preferenses, and last user did't create it neiher. When i try to change user, i can only see account of last user. I go to <accounts>, and it shows me that:
    Last login: Thu Feb  9 23:40:41 on ttys000
    MacBook-Pro:~ *n*y*o*d*$ /Library/PreferencePanes/Growl.prefPane/Contents/MacOS/Growl ; exit;
    -bash: /Library/PreferencePanes/Growl.prefPane/Contents/MacOS/Growl: cannot execute binary file
    logout
    [Process completed]
    I'm really sorry, but it is my frst mac and i dont understan anything..
    Thank you

  • How  to track System.exit(0) call

    hi there,
    how can i trace the System.exit(0) function call in my program.
    i.e as we know which class is being loaded into the jvm by overriding
    the classloader, can we similarly know when is our jvm going to be
    destroyed. here iam invoking jvm from my windows program using invocation api.
    any help is mostly appreciated.
    thanks in advance
    bye
    ramana

    Not sure I know what you are asking.
    You could create a security manager which prevents exit() from being called.
    You could replace System using the bootstrap command line option. Although if you do that you can not distribute it due to the license agreement. Once replaced you can do anything you want in the application.
    You could use Runtime.addShutdownHook() if you just want to do something when the application exits.

  • System.exit(0)   error in program.

    Any help appreciated. Let me first put my code here:
    Converts money using CurrencyConverter, there's another class I haven't posted here!! (which calculates conversion)
    import java.util.* ;
    public class CurrencyConverterTester
      public static void main(String[] args)
        Scanner in = new Scanner(System.in) ;
        System.out.println("How many euros is one dollar?") ;
        String input = in.nextLine() ;
        double rate = Double.parseDouble(input) ;
        CurrencyConverter myconverter = new CurrencyConverter(rate);
        System.out.println("Dollar value (Q to quit)") ;
        input = in.nextLine() ;
        while (true) {
          if (input == "Q"){
            System.exit(0);
            break;}
          else {
          System.out.println(input + " dollar = " +  myconverter.convert(Double.parseDouble(input)) + " euros");
          input = in.nextLine();
          continue;}   
    }The issue is that the program won't terminate when I enter Q as my input?? I'm guessing it might have something to do my conversion from string to double in the 'else' statement, but not sure. Also, if you can suggest a more simpler method for the last 'while' statement, that would be helpful as well. Thanks. (noob to java)

    paulcw wrote:
    Curse Gosling for making &#43; syntactic sugar for string append, but not overloading any other operators.@Paul
    What did you expect from a duck ;-)
    Seriously, yep, maybe it would have been better for noobs if the syntax of Java Strings was consistent with other kinds of Object... or maybe it would have been better if == was compiler-magiced into stringA.equals(stringB)... and the left and right shift operators have promise, and of course that way lies MADNESS, as witnessed in C&#43;&#43; ;-)
    @OP... You are (IMHO) using the break, continue and especially System.exit() inappropriately... see my comments in your code...
        System.out.println("Dollar value (Q to quit)") ;
        input = in.nextLine() ;
        // while-true-loops are a "fairly usual" way of doing this kind of stuff,
        // but that doesn't make them "the preferred option". Typically you would
        // explore more "vanilla approaches" (which don't rely on the break and
        // continue statements)... leaping straight to the "tricky approach" means
        // you haven't (most often out of sheer laziness) thought it through... and
        // ALL good computer programs are thoroughly thought through (yep, try
        // saying that three times fast, especially after three beers).
        while (true) {
          // You don't compare Strings using ==
          if ( "Q".equalsIgnoreCase(input) ) {
            // Either of the following statements will do the job. The call to exit
            // will exit the JVM, therfore the break statement cannot be reached,
            // so it is superflous, so it's presence is just a bit confusing. Having
            // said that, "real programmers" don't use System.exe routinely, only in
            // the case of an emergency, such as handling a fatal-error, such as an
            // out-of-memory condition... an even then it's usually indicative of a
            // poor "system design", because it terminates the JVM which is running
            // this program without giving anything else in the program a chance to
            // clean-up after itself... like ask the user if they want to save there
            // work, or whatever.
            // I would use break (if anything) instead of System.exit
            // ... and if I wrote the Java tutorials, exit wouldn't be mentioned at
            // all until both "normal" flow control, and exception handling had both
            // been thoroughly covered.
            System.exit(0);
            break;
          } else {
            // I would break this line up, probably into three lines, simply becuase
            // it's syntatically "a long line".
            // Also the name "myconverter" doesn't tell what the class is/does.
            // IMHO, currencyConverter would be a better (more meaningful) name.
            // HERE'S HOW I WOULD WRITE IT
            // double dollars = Double.parseDouble(input);
            // double euros = currencyConverter.convert(dollars);
            // System.out.println(input + " dollar = " + euros + " euros");
            System.out.println(input + " dollar = " +  myconverter.convert(Double.parseDouble(input)) + " euros");
            input = in.nextLine();
            // This continue statement is superflous. continue says "go back to the
            // top of loop, reevaluate the loop-condition (true in this case) and
            // (if the condition is still true) "Play it again Sam".
            // ... which is exactly what will happen without this continue statement
            // and hence (IMHO) your code is easier to follow without it, simply
            // because another programmer may waste there time trying to figure out
            // WHY that continue statement is present.
            continue;
        }*ALSO:* The format of that code totally sucks. Braces all over the place; improper indentation. No wonder you're struggling to read your own code. Please read and abide the [The Java Code Conventions|http://java.sun.com/docs/codeconv/] (at least until you have the requisite experience to formulate credible and compelling arguments as to why your "style" is superior to the standard, and that's no small ask). Yes this is *important*... trust me on this (for now)... especially if you are going to ask for help on the forums... You're effectively wasting our time asking us to decipher your code because you are too lasy to format it correctly... and I for one find that "self entitled" attitude ugly, and offensive... Help us help you... you know?
    And BTW.... Here's how I would actually do it.... no funky while-true, break, or continue... just a plain-ole'-while-woop....
    package forums;
    import java.util.Scanner;
    public class KRC
      private static final Scanner SCANNER = new Scanner(System.in);
      public static void main(String[] args) {
        try {
          String input = null;
          while ( !"Q".equalsIgnoreCase(input=enterDollarAmount()) ) {
            System.out.println(input + " dollars is " +  Double.parseDouble(input) + " euros.");
            System.out.println();
        } catch (Exception e) {
          e.printStackTrace();
      private static String enterDollarAmount() {
        System.out.print("Please enter an amount in dollars : ");
        return SCANNER.nextLine();
    }Edited by: corlettk on 25/10/2009 10:21 ~~ Distant Monarching Forum Markup!

Maybe you are looking for

  • Samsung Galaxy Tab Pro

    I was told that Adobe Cloud Services (apps like Photoshop) could run on tablets like Samsung's Galaxy Tab PRO model and/or the Note Pro. Is this true? Anyone know?

  • So can you install Windows 8.1? Is it simple?

    I just purchased the higher-end 15 inch late 2013 MacBook Pro, and didn't purchase the additional USB SuperDrive. Using Bootcamp I either want to set up a Windows 7 or Windows 8.1 partition. But I seem to be reading different takes on what works and

  • Need Advice with Syncing Contacts Please

    Hi, I was originally going to post a question asking "How can I transfer my contacts from my iPhone to my iMac Address Book (which is currently empty)?" However, after spending over an hour searching for an answer online, it sounds like there's no ea

  • Adobe form not saving data.

    hi Experts, I am facing strange problems with Adobe forms. I am working on both Offline and online adobe forms. adobe form which i make does not allow to save data. I am using the Adobe liveCycle designer 7.1. The Adobe reader version is 7.08 and ser

  • How to send username and password

    Hello Friends, When a BSP application is tested or executed, it opens a explorer window and asks for the server username and password. Is there a way where I can pass the username and password through the url so that the user nedd not know the userna