简体   繁体   中英

How to limit the execution time of a third-party Java method

In a Java program I need to execute a method of a third-paryt java class. I use Class.forName to get a class and newInstance() to get an object of this class:

Class  class  = Class.forName(className);
AClass object = (AClass) class.newInstance(); 

Then I execute and get a result of the desired method with

ResultObject result = object.method();

So far, so good. But the problem appears if I want to limit the execution time of the method (ie, if the method doesn't stop after a given number of seconds, I would like to kill this execution and ignore the result).

An ideal solution would be to run the method in a separate thread and to stop&destroy this thread if the method doesn't finish in time. But unfortunately a thread CAN NOT BE STOPED (it's stop() method is deprecated) and I can not rely on correct interrupt-behaviour of the third-party method.

Is there any other way to execute a method and to have a full control over its execution (ie to be able to kill it any time)? I am sure that this is possible - Netbeans, for example, can execute my class (when I run my application) and it can kill it if I press stop button. But how does Netbeans (or Eclipse or any othe IDE) manage to do this?

Any idea? Thanks!

One option would be to run the 3rd party code not just in a seperate thread, but in a seperate process. It's a hassle, but you can kill the process whenever you want to and it's guaranteed to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM