Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a method which have infinite loop via reflection in java

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?

like image 494
Akhilesh Dhar Dubey Avatar asked Nov 30 '25 04:11

Akhilesh Dhar Dubey


1 Answers

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

like image 88
Nathan Hughes Avatar answered Dec 02 '25 19:12

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!