Karthik207
Karthik207

Reputation: 493

Null Pointer exception with callable in java

I am using executor service to spawn multiple callable threads for parallel execution. In the call method (overridden) of the class which implements callable, I check for a specific data. If the data is present I will return the data, else I will return null. When I execute the code, I'm getting NullPointerException. Can we return null from call method?

Basically of this syntax:

public string call ()
{
if (data)
return data;
else
return null;
}

Something of this kind.

Upvotes: 1

Views: 4939

Answers (1)

upog
upog

Reputation: 5531

yes you can return null, below is the sample code which is working fine, Probably in the call method you would have been accessing an object which is not created

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;


public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executorService1 = Executors.newFixedThreadPool(4);     
        Future f2 =executorService1.submit(new callable());
        System.out.println("f2 " + f2.get());       
        executorService1.shutdown();
    }

}


class callable implements Callable<String> {
    public String call() {       
        if(1==1)
           return null;
        return Thread.currentThread().getName();
    }
}

Upvotes: 1

Related Questions