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>?
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.
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 .
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.
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
Should I declare them
Callable<Void>andFuture<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.
I think you should declare them Callable<?> and Future<?>. Then you can implement them anyway you want including Callable<Void> and Future<Void>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With