J.Doe J.Doe - 2 months ago 19
Java Question

ExecutorService unchecked assignment

I'm learning about ExecutorService and Callables, but get a warning from intelij saying I'm doing an unchecked assignment for this line:

Future<OrderWorker<OfferType>> future = executorService.submit(new OrderWorker<OfferType>(anOfferSet));


I don't get how to assign correctly. Here's the code:

ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<OrderWorker<OfferType>>> futures = new ArrayList<>();
for (OfferType anOfferSet : offerSet) {
// the next assignment is unchecked:
Future<OrderWorker<OfferType>> future = executorService.submit(new OrderWorker<OfferType>(anOfferSet));
futures.add(future);
}





Order Worker:

public class OrderWorker<I extends OfferType> implements DataWorker {
private Logger log = Logger.getLogger(OrderWorker.class);
private final OfferType offer;

public OrderWorker(I data) {
this.offer = data;
}

public OfferType getOffer() {
return offer;
}

@Override
public Object call() throws Exception {
Thread.sleep(5000);
log.info(offer.getListingPrice().getAmount());
return this;
}
}


DataWorker interface:

interface DataWorker<I extends OfferType> extends Callable<I> {}


OfferType
is a simple POJO class.

EDIT

I also tried to give DataWorker a type when implementing it:

public class OrderWorker<I extends OfferType> implements DataWorker<I>


This gives an error saying call() in OrderWorker clashes with call() in Callable -> incompatible return type

What am I doing wrong, and what do I have to do to make the assignment checked?

Answer

What you need to change is the declaration of OrderWorker and the return type of call, as next:

public class OrderWorker<I extends OfferType> implements Callable<OrderWorker<I>> {
    ...
    @Override
    public OrderWorker<I> call() throws Exception {
        ...
    }
}
Comments