IDE-Style program running

前端 未结 1 852
死守一世寂寞
死守一世寂寞 2020-12-06 08:42

My Goal


I am attempting to make a Java program in which a user can select any .class or .jar file from their computer. My program w

相关标签:
1条回答
  • 2020-12-06 08:57

    If you don't want the other program (which you call through it's main method) to be able to shut down the JVM you're running in, you have, as I see it, three options:

    1. Using a SecurityManager

    Set up the SecurityManager so that it prevents the System.exit call:

    public class Test {
        public static void main(String args[]) {
            SecurityManager sm = System.getSecurityManager();
            System.setSecurityManager(new SecurityManager() {
                @Override
                public void checkExit(int status) {
                    throw new SecurityException("Client program exited.");
                }
            });
    
            try {
                System.out.println("hello");
                System.exit(0);
                System.out.println("world");
            } catch (SecurityException se) {
                System.out.println(se.getMessage());
            }
        }
    }
    

    Prints:

    hello
    Client program exited.
    

    This is probably the nicest solution. This is the way application servers prevent an arbitrary servlet from terminating the entire server.

    2. Separate JVM

    Run the other program in a separate JVM, using for instance ProcessBuilder

    import java.io.*;
    
    public class Test {
        public static void main(String args[]) throws IOException {
    
            ProcessBuilder pb = new ProcessBuilder("java", "other.Program");
            pb.redirectErrorStream();
            Process p = pb.start();
            InputStream is = p.getInputStream();
            int ch;
            while ((ch = is.read()) != -1)
                System.out.print((char) ch);
            is.close();
            System.out.println("Client program done.");
        }
    }
    

    3. Use shutdown hooks instead

    Don't disallow the termination of the JVM, but instead add shutdown-hooks that cleans up the "hub" and exits gracefully. (This option probably only makes sense if your running one "external" program at a time.)

    import java.io.*;
    
    public class Test {
    
        public static void main(String args[]) throws IOException {
    
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() { 
                    System.out.println("Uninitializing hub...");
                    System.out.println("Exiting gracefully.");
                }
            });
    
            // Run client program
            System.out.println("Running... running... running...");
            System.exit(0);
    
         }
    }
    

    Prints:

    Running... running... running...
    Uninitializing hub...
    Exiting gracefully.
    
    0 讨论(0)
提交回复
热议问题