Reputation: 31
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 (i.e., 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 (i.e. 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!
Upvotes: 3
Views: 704
Reputation: 2826
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.
Upvotes: 5