I would like to execute different methods in a separate thread depending on the parameters that are assigned to the constructor.
So, when you send Callable to ExecutorService , you get the future with the same type:
Future<String> stringResult = executor.submit(new MyCallable<String>()); Future<Integer> stringResult = executor.submit(new MyCallable<Integer>());
What you cannot do is have one Future result that returns one of two different types: String or Integer , based on the arguments when building the ExecutorService . I think this is what you are asking for.
One option is to create a small wrapper class:
public class StringOrInteger { final String s; final Integer i; public StringOrInteger(String s) { this.s = s; this.i = null; } public StringOrInteger(Integer i) { this.s = null; this.i = i; } public boolean isString() { return this.s != null; } }
Then your executor will send a Callable<StringOrInteger> , and the StringOrInteger instances returned by Future<StringOrInteger> will either be set to s or i .
An extremely ugly alternative would be to return Object and use instanceof to figure out what type it is. But I wonβt even show the code for this implementation, because it will give me hives.
source share