Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare Callable to execute function returning void in Java?

Suppose I would like to run static method foo asynchronously

void foo() throws Exception {...} 

Since foo throws an exception I would prefer create a Callable and invoke ExecutorService.submit with it to get a Future.

Now I wonder how to declare those Callable and Future properly. Should I declare them

Callable<Void> and Future<Void>?
like image 700
Michael Avatar asked Aug 29 '13 13:08

Michael


People also ask

How do you execute a Callable in Java?

For supporting this feature, the Callable interface is present in Java. For implementing Runnable, the run() method needs to be implemented which does not return anything, while for a Callable, the call() method needs to be implemented which returns a result on completion.

Can Callable return null?

Overview. callable() is a static method of the Executors class that returns a Callable . When called, it runs the passed Runnable task and returns null .

How do you declare a void variable in Java?

Since JDK 1.1, Java provides us with the Void type. Its purpose is simply to represent the void return type as a class and contain a Class<Void> public value. It's not instantiable as its only constructor is private. Therefore, the only value we can assign to a Void variable is null.

Can you return void in Java?

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.


2 Answers

Should I declare them Callable<Void> and Future<Void>?

Yes.

Void is similar to the wrapper classes Integer, Long etc. for the primitive types int, long etc. You could say it's a wrapper class for void, even though void is not really a type.

like image 156
Jesper Avatar answered Oct 05 '22 12:10

Jesper


I think you should declare them Callable<?> and Future<?>. Then you can implement them anyway you want including Callable<Void> and Future<Void>.

like image 40
emory Avatar answered Oct 05 '22 12:10

emory