Home > Net >  How to declare Futures in Java without warnings?
How to declare Futures in Java without warnings?

Time:12-09

Trying to use Futures and IntelliJ is giving me various warnings, not sure how to code it 'correctly'. The code works but obviously want to learn best practice.

try {
    public void  futuresTest() {
        try {
            List<String> valuesToProcess = List.of("A","B","C","D","E");
            
            ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            List<Future<MyObject>> futures = new ArrayList<>();

            for(String s : valuesToProcess) {
                futures.add((Future<MyObject>) executor.submit(new MyObject(s)));     //<THIS
            }

            LOG.info("Waiting for threads to finish...");
            boolean termStatus = executor.awaitTermination(10, TimeUnit.MINUTES);
            
            if (termStatus) {
                LOG.info("Success!");
            } else {
                LOG.warn("Timed Out!");
                for(Future<MyObject> f : futures) {
                    if(!f.isDone()) {
                        LOG.warn("Failed to process {}:",f);
                    }
                }
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

Gives Unchecked cast: 'java.util.concurrent.Future<capture<?>>' to 'java.util.concurrent.Future<model.MyObject>'

            List<Future> futures = new ArrayList<>();

            for(String s : valuesToProcess) {
                futures.add(  executor.submit(new MyObject(s)));
            }

Gives Raw use of parameterized class 'Future'

is it just supposed to be List<Future<?>> futures = new ArrayList<>(); that has no warnings but I would think I should be specifying my Object.

CodePudding user response:

Based on the comments it does sound like the correct approach is

List<Future<?>> futures = new ArrayList<>();

for(String s : valuesToProcess) {
    futures.add(executor.submit(new MyObject(s)));
}
  • Related