修复未来未检查的分配警告

时间:2016-02-06 12:50:42

标签: java concurrency future executorservice

我有一个代码可以ping给定子网络中的所有IP地址。它使用并发来提高性能,因为等待每个IP地址的超时会花费更长的时间,否则:

/**
 * @param subNetwork The subnet to scan
 * @return A list of internet protocol addresses that are reachable
 * @throws IOException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public static List<String> getRespondingInternetProtocolAddresses(final String subNetwork) throws IOException,
        ExecutionException,
        InterruptedException
{
    final List<String> activeInternetProtocolAddresses = new ArrayList<>();
    int startingIndex = 1;
    int upperBound = 256;
    int poolSize = upperBound - 1; // Query concurrently for best time savings
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    List<Future<Runnable>> tasks = new ArrayList<>();

    for (int currentSubNetIndex = startingIndex; currentSubNetIndex < upperBound;
         currentSubNetIndex++)
    {
        final int subNetIndex = currentSubNetIndex;

        // Query each Internet protocol address concurrently for speed purposes
        Future task = threadPool.submit(new Thread(() ->
        {
            String currentInternetProtocolAddress = subNetwork + "." + subNetIndex;

            try
            {
                if (Ping.isReachable(currentInternetProtocolAddress))
                {
                    activeInternetProtocolAddresses.add(currentInternetProtocolAddress);
                }
            } catch (IOException exception)
            {
                exception.printStackTrace();
            }
        }));

        tasks.add(task); // TODO Fix unchecked assignment warning
    }

    for (Future<Runnable> task : tasks)
    {
        task.get();
    }

    threadPool.shutdown();

    return activeInternetProtocolAddresses;
}

将新任务添加到任务列表时,我收到一个未经检查的分配警告:

tasks.add(task);

我尝试通过将Future<Runnable>替换为Future来生成submit(),但由于{{3}}返回Future<?>,因此创建了编译错误。

我该怎么做才能解决警告?

2 个答案:

答案 0 :(得分:1)

要解决此问题,您可以将任务声明为List<Future<?>>task Future<?>

答案 1 :(得分:0)

如果某个类型Future<T>的结果应该从任务返回,则使用

T - 然后你得到这个结果并使用它。

如果您只需等待所有任务执行,请使用threadPool.submit(Runnable r)。然后在threadPool.shutdown()调用threadPool.awaitTermination()之后 - 阻止所有任务完成。