keeping_it_simple
keeping_it_simple

Reputation: 469

usage of generic in Callable and Future interface?

What's the use of generic in Callable interface?

Consider this code which I copied from https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6:

import java.util.\*;
import java.util.concurrent.\*;

public class CallableExample {

  public static class WordLengthCallable
        implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future<Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}

Integer in Callable<Integer> and Future<Integer> is not being used. It could be anything else as well like Callable<String> and Future<String> and code will still work.

I understand usage of Generics and appreciates its usage specially in collections.

Thanks.

Upvotes: 2

Views: 3576

Answers (2)

Ajay George
Ajay George

Reputation: 11875

John has a given a correct answer. Just adding the importance of not ignoring compiler warnings. While compiling your current code the compiler warns you for unchecked conversion.

$ javac -Xlint:unchecked CallableExample.java
CallableExample.java:22: warning: [unchecked] unchecked conversion
found   : CallableExample.WordLengthCallable
required: java.util.concurrent.Callable<java.lang.Integer>
            Callable<Integer> callable = new WordLengthCallable(word);
                                         ^
1 warning

Integer in Callable<Integer> and Future<Integer> is not being used. It could be anything else as well like Callable<String> and Future<String> and code will still work.

Change your class to use implements Callable<Integer>

The compiler becomes happy and your code won't work if you start using Callable<String> and Future<String> everywhere.

Upvotes: 3

John B
John B

Reputation: 32969

The point of Callable vs Runnable is the ability in Callable to return a value (retrievable via Future if using an ExecutorService). They could have coded it to just return Object and make the code cast but then there would be absolutely no compile-time checking. Seems logical to make Callable generic to specify the return type so that you don't need the explicit cast and you have compile-time checking.

Of course, due to type-erasure this all goes away at run-time but that does not reduce its value WRT intent and compile-time.

Upvotes: 6

Related Questions