Future.get(5,TimeUnit.SECONDS) doesnt timeout after 5 seconds if native methods are used in Java

1k Views Asked by At

I am using Executor framework in my java code. I am facing an issue and i need clarification regarding the same. Below is my java code,

ExecutorService executorObj = Executors.newFixedThreadPool(10);
        String name = "default";
        Future<String> futRes =  executorObj.submit(new Callable<String>() {
            @Override
            public String call() {
                computePropertyPage("");
                return "Hello";
            }
        }); 

        try {
            System.out.println("waiting for name for 5 seconds maximum...");
             return futRes.get(5,TimeUnit.SECONDS);
        } catch (Exception e) { 
            System.out.println("Exception occurred : " + e);
            return name;
        } 

In the above code, computePropertyPage() is a native method. Its properly linked with the java code. But the call to the function is not getting completed. Its stuck indefinitely. If the call is stuck for more than 5 seconds, i am expecting TimeOutException after 5 seconds. But i am not recieving it.

Instead of native method call, if i just add a sleep of 10 seconds as below,

try {
        Thread.sleep(10000);    
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I get TimeOutException.

I just want to know if its the limitation from the java side that it dont have control on the native methods and thats the reason its not able to throw TimeOutException for futRes.get(5,TimeUnit.SECONDS);

1

There are 1 best solutions below

4
Sukhpal Singh On

Your method computePropertyPage completes in less than 5 seconds and return response. Since you aren't calling shutdown on ExecutorService it isn't terminating. Try calling executorObj.shutdown();