簡體   English   中英

Java JNI和Future Task

[英]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()放在哪里。 有2個位置被評論。
  • 如果我使用timeOutInSeconds = 0運行此函數,它將完美運行。 但是,無論timeOutInSeconds的值如何,任務都會陷入困境,並且不會調用JNI任務。 我通過將printf放在JNI代碼中來檢查這一點。 任務需要1秒才能執行,我給了30秒,5分鍾等等,但它仍然被卡住了。

這種方法有問題嗎?

你可以(在這種情況下應該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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM