Reputation: 3412
I'm trying run some javascripts in java. I'm not sure if the scripts are correct and I'd like to kill the the invocation after a time period. This is how i run the scripts.
returnMethod = invocableEngine.invokeFunction("main", input);
My idea was to run something like a deamon thread, which starts second thread with a timeout. The second thread - ScriptEvaluator runs the invocable function, described above. ScriptEvaluator implements Runnable.
ScriptEvaluator se = new ScriptEvaluator(r);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(Executors.callable(se)), timeout, TimeUnit.MILLISECONDS);
executor.shutdownNow();
Well it doesn't work. After timeout the Thread still runs.
Another requirement is that only one SkriptEvaluator thread is running.
EDIT: I've found something very interesting in shutdownNow(). When it doesn't guarantees the stopping of the Threads, is there guaranteed way to do that?
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
Thanks in advance
Upvotes: 1
Views: 283
Reputation: 440
Executor.shutdownNow()
does not always work properly, perhaps you'll need Thread.stop()
as the hardcore solution.
Upvotes: 0
Reputation: 31182
You can test how ScriptEvaluator()
responds to Thread.interrupt()
. If it's well written, then executor.shutdownNow()
will work. If it's not, then there is no perfect solution.
However, assuming your javascript doesn't interact with your main code a that much, you can use Thread.stop(). If you decide to do this, then make sure you understand why not to use Thread.stop() in general.
Upvotes: 2