Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit task which implements a subinterface of Callable<T> to an ExecutorService

Tags:

java

generics

How to submit task which implements a subinterface of Callable<T> to an ExecutorService?

I have a subinterface of Callable<T> defined as:

public interface CtiGwTask<T>
    extends Callable {

    ...
}

It just defines some static constants but adds no methods.

Then I have the following method where execService is a FixedThreadPool instance.

@Override
public CtiGwTaskResult<Integer> postCtiTask(CtiGwTask<CtiGwTaskResult<Integer>> task) {

    Future<CtiGwTaskResult<Integer>> result =
            execService.submit(task);

    try {
        return result.get();

    } catch (InterruptedException | ExecutionException ex) {
        LOGGER.log(Level.FINEST,
                "Could not complete CTIGwTask", ex);
        return new CtiGwTaskResult<>(
                CtiGwResultConstants.CTIGW_SERVER_SHUTTINGDOWN_ERROR,
                Boolean.FALSE,
                "Cannot complete task: CTIGateway server is shutting down.",
                ex);
    }
}

Unfortunately this is giving 2 unchecked conversion and 1 unchecked method invocation warnings.

...\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked conversion
            execService.submit(task);
required: Callable<T>
found:    CtiGwTask<CtiGwTaskResult<Integer>>
where T is a type-variable:
  T extends Object declared in method <T>submit(Callable<T>)

...\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked method invocation: method submit in interface ExecutorService is applied to given types
            execService.submit(task);
required: Callable<T>
found: CtiGwTask<CtiGwTaskResult<Integer>>
where T is a type-variable:
  T extends Object declared in method <T>submit(Callable<T>)

...\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked conversion
            execService.submit(task);
required: Future<CtiGwTaskResult<Integer>>
found:    Future

If I change the submit call to

Future<CtiGwTaskResult<Integer>> result =
    execService.submit( (Callable<CtiGwTaskResult<Integer>>) task);

Then everything seems to work but now I get an unchecked cast warning.

...\src\com\dafquest\ctigw\cucm\CtiGwWorkerImpl.java:151: warning: [unchecked] unchecked cast
            execService.submit((Callable<CtiGwTaskResult<Integer>>) task);
required: Callable<CtiGwTaskResult<Integer>>
found:    CtiGwTask<CtiGwTaskResult<Integer>>

So what I'm I missing? Shouldn't submit() apply to an instance of a subclass of Callable?

like image 484
AndRAM Avatar asked May 15 '13 12:05

AndRAM


1 Answers

You are using the raw Callable type.

Change:

public interface CtiGwTask<T> extends Callable

to this:

public interface CtiGwTask<T> extends Callable<T>
like image 96
Bohemian Avatar answered Nov 04 '22 12:11

Bohemian