Java JNI and the future task

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)
        {
            // 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();
}

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?

+3
source share
1 answer

( ) future.cancel() finally. http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html.

2- , , , timeOutInSeconds = 0. ? JNI_TASK()?

+2

All Articles