[英]Java JNI and Future Task
我正在嘗試實現一個代碼,我想從JNI調用一個應該有超時的函數。 如果超過超時,我想終止本機任務。 我發布了一段代碼作為示例。
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)
{
// handle the timeout
kill_task_in_JNI();
// future.cancel(true);
return TIMEOUT;
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
}
finally
{
// future.cancel(true);
executor.shutdown();
}
}
else
JNI_Task();
}
有幾個問題 -
這種方法有問題嗎?
你可以(在這種情況下應該future.cancel()
只在finally塊中調用future.cancel()
。 http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html 。
關於第二個問題,如果timeOutInSeconds = 0時問題也出現,我不清楚。 是這樣的嗎? 你能提供JNI_TASK()方法的內容嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.