I am trying to implement code where I want to call a function from JNI that must have a timeout. If it exceeds the timeout, I want to finish my own task. As an example, I am posting a piece of code.
void myFunction(timeOutInSeconds)
{
if(timeOutInSeconds > 0)
{
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Integer> task = new Callable<Integer>() {
public Integer call() {
System.out.println("Calling JNI Task");
JNI_Task();
System.out.println("Finished JNI Task");
return 0;
}
};
Future<Integer> future = executor.submit(task);
try
{
@SuppressWarnings("unused")
Integer result = future.get(timeOutInSeconds, TimeUnit.SECONDS);
}
catch (TimeoutException ex)
{
kill_task_in_JNI();
return TIMEOUT;
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
finally
{
executor.shutdown();
}
}
else
JNI_Task();
}
There are a few questions -
- Where should I specify future.cancel () exactly. There are 2 locations that are commented on.
- If I run this function with timeOutInSeconds = 0, it works fine. However, regardless of the value of timeOutInSeconds, the task is stuck and the JNI task is not called. I test this by putting printf in the JNI code. The task takes 1 second, and I gave 30 seconds, 5 minutes, etc. stuck.
Is there a problem with this approach?
source
share