How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?

后端 未结 7 1763
陌清茗
陌清茗 2020-11-30 08:55

I have a method that I would like to call. However, I\'m looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.

I\'m

相关标签:
7条回答
  • 2020-11-30 09:44

    The correct answer is, I believe, to create a Runnable to execute the sub-program, and run this in a separate Thread. THe Runnable may be a FutureTask, which you can run with a timeout ("get" method). If it times out, you'll get a TimeoutException, in which I suggest you

    • call thread.interrupt() to attempt to end it in a semi-cooperative manner (many library calls seem to be sensitive to this, so it will probably work)
    • wait a little (Thread.sleep(300))
    • and then, if the thread is still active (thread.isActive()), call thread.stop(). This is a deprecated method, but apparently the only game in town short of running a separate process with all that this entails.

    In my application, where I run untrusted, uncooperative code written by my beginner students, I do the above, ensuring that the killed thread never has (write) access to any objects that survive its death. This includes the object that houses the called method, which is discarded if a timeout occurs. (I tell my students to avoid timeouts, because their agent will be disqualified.) I am unsure about memory leaks...

    I distinguish between long runtimes (method terminates) and hard timeouts - the hard timeouts are longer and meant to catch the case when code does not terminate at all, as opposed to being slow.

    From my research, Java does not seem to have a non-deprecated provision for running non-cooperative code, which, in a way, is a gaping hole in the security model. Either I can run foreign code and control the permissions it has (SecurityManager), or I cannot run foreign code, because it might end up taking up a whole CPU with no non-deprecated means to stop it.

    double x = 2.0;  
    while(true) {x = x*x}; // do not terminate
    System.out.print(x); // prevent optimization
    
    0 讨论(0)
提交回复
热议问题