有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个代码,可以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<?>

我可以做些什么来修复警告


共 (2) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    Future<T>用于从任务中返回类型为T的结果,然后获得该结果并使用它

    如果只需要等待所有任务执行,请使用threadPool.submit(Runnable r)。然后在threadPool.shutdown()之后调用^{}来阻止,直到所有任务完成