Invoking a method which have infinite loop via reflection in java

1.5k Views Asked by At

I created an editor which have compile and run option for a java source file. The problem is that when i run a method by reflection which have infinite loop, the editor hanged...

        Method thisMethod = thisClass.getDeclaredMethod("main", String[].class);
        thisMethod.invoke(null, (Object) new String[0]);  

If the main method have infinite loop like:

        public static void main(String[] args) {
             while(true)
             System.out.println("loop ");
        }

Then i have to quit the Editor explicitly from task manager.

I want to add an functionality which provide forcefully stop running of the program if it occurs an infinite loop.

So, how to stop a running method which have infinite loop?

2

There are 2 best solutions below

0
On

Running the code in a separate process (and providing a button to kill the process with once the user gets tired of waiting for it) would be the most straightforward way.

If you have only one process and are running this code in a separate thread, then that's not as good. There's no general safe way to stop a thread without the thread's cooperation, unless you use the deprecated stop method. Using a separate process would maintain separation and limit the damage the user's program could do to your editor. The user can pick a JVM different from the one your editor uses to run against, and your classloaders stay separate from the ones used by the user's code.

To do this you'd create a new process using ProcessBuilder and run it, making sure you read from its stdout and stderr streams. (You'll want to do that anyway to show the user the output, but if you let the buffers fill up the process will hang.)

0
On

You can try the ExecutorService from java8.

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        while(true)
        System.out.println("loop ");

    });
    executor.awaitTermination(10, TimeUnit.SECONDS);