user35662
user35662

Reputation: 37

Why java creates error to cast a object as callable?

I am trying to run CompletionService to execute number of threads.Here is my code

CompletionService<ReadProcess_MongoDB> taskCompletionService;
    taskCompletionService = new ExecutorCompletionService<ReadProcess_MongoDB>(pool);

 Collection<Callable<ReadProcess_MongoDB>> list = new LinkedList<Callable<ReadProcess_MongoDB>>();
       list.add((Callable<ReadProcess_MongoDB>) new ReadProcess_MongoDB(0));
       list.add((Callable<ReadProcess_MongoDB>) new ReadProcess_MongoDB(1));

Java shows runtime error at list.add.
Eror:-( cannot be cast to java.util.concurrent.Callable).

Upvotes: 0

Views: 1050

Answers (2)

chiastic-security
chiastic-security

Reputation: 20520

In this line

list.add((Callable<ReadProcess_MongoDB>) new ReadProcess_MongoDB(0));

you're trying to cast your new ReadProcess_MongoDB(0) as a Callable<ReadProcess_MongoDB>. If this fails, it's because your ReadProcess_MongoDB class isn't castable to Callable<ReadProcess_MongoDB>; and that can only be because you didn't implement Callable<ReadProcess_MongoDB> in that class.

Declare it as

public class ReadProcess_MongoDB implements Callable<ReadProcess_MongoDB> {
    //...
}

You will then need to ensure that your class implements the methods of the Callable interface. There's only one: the call() method.

(Be clear in your own mind that this is really what you want, though. Are you sure you don't want it to implement Callable<T> for some other type T?)

Upvotes: 1

LD.
LD.

Reputation: 418

The java compiler says that the ReadProcess_MongoDB class is not a sub-class of the java.util.concurrent.Callable class.

  • Is it another Callable class you meant ? in this case you should specify the full package name in your cast: package.Callable
  • Otherwise, you may need to implement the Callable class/interface to use the ReadProcess_MongoDB object you create.

Upvotes: 0

Related Questions