How to limit execution time of 3rd party Java method
In a Java program, I need to execute a method of the ja-paryt java class. I am using Class.forName
to get a class and newInstance()
to get an object of that class:
Class class = Class.forName(className);
AClass object = (AClass) class.newInstance();
Then I execute and get the result of the desired method with
ResultObject result = object.method();
So far so good. But the problem arises if I want to limit the execution time of a method (i.e., if the method does not stop after a given number of seconds, I would like to kill this execution and ignore the result).
The ideal solution is to run a method on a separate thread and stop and kill that thread if the method doesn't complete in time. But unfortunately the thread cannot be stopped (the method is stop()
deprecated) and I cannot rely on the correct interrupt behavior of the third party method.
Is there another way to execute a method and have full control over its execution (i.e. be able to kill it at any time)? I'm sure this is possible - Netbeans, for example, can execute my class (when my application starts) and it can kill it if I hit the stop button. But how does Netbeans (or Eclipse or any other IDE) deal with this?
Any idea? Thank you!
source to share