Guide to java.util.concurrent.Future – java.util.concurrent.Future指南

最后修改: 2017年 2月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll learn about Future. An interface that’s been around since Java 1.5, it can be quite useful when working with asynchronous calls and concurrent processing.

在本教程中,我们将学习Future。这个接口从Java 1.5开始就存在了,在处理异步调用和并发处理时,它可能相当有用。

2. Creating Futures

2.创造前景

Simply put, the Future class represents a future result of an asynchronous computation. This result will eventually appear in the Future after the processing is complete.

简单地说,Future类代表了一个异步计算的未来结果。这个结果最终会在处理完成后出现在Future中。

Let’s see how to write methods that create and return a Future instance.

让我们看看如何编写创建和返回Future实例的方法。

Long running methods are good candidates for asynchronous processing and the Future interface because we can execute other processes while we’re waiting for the task encapsulated in the Future to complete.

长期运行的方法是异步处理和Future接口的良好候选者,因为我们可以在等待Future中封装的任务完成时执行其他进程。

Some examples of operations that would leverage the async nature of Future are:

一些可以利用Future的异步特性的操作的例子是。

  • computational intensive processes (mathematical and scientific calculations)
  • manipulating large data structures (big data)
  • remote method calls (downloading files, HTML scrapping, web services)

2.1. Implementing Futures With FutureTask

2.1.使用FutureTask实现Futures

For our example, we’re going to create a very simple class that calculates the square of an Integer. This definitely doesn’t fit the long-running methods category, but we’re going to put a Thread.sleep() call to it so that it lasts 1 second before completing:

在我们的例子中,我们将创建一个非常简单的类,计算Integer的平方。这绝对不符合长期运行方法的范畴,但是我们要给它加上一个Thread.sleep()的调用,使它在完成之前持续1秒。

public class SquareCalculator {    
    
    private ExecutorService executor 
      = Executors.newSingleThreadExecutor();
    
    public Future<Integer> calculate(Integer input) {        
        return executor.submit(() -> {
            Thread.sleep(1000);
            return input * input;
        });
    }
}

The bit of code that actually performs the calculation is contained within the call() method, and supplied as a lambda expression. As we can see, there’s nothing special about it, except for the sleep() call mentioned earlier.

实际执行计算的代码包含在call()方法中,并以lambda表达式的形式提供。正如我们所看到的,除了前面提到的sleep()调用外,并没有什么特别之处。

It gets more interesting when we direct our attention to the use of Callable and ExecutorService.

当我们把注意力放在CallableExecutorService的使用上时,情况变得更加有趣。

Callable is an interface representing a task that returns a result, and has a single call() method. Here we’ve created an instance of it using a lambda expression.

Callable是一个接口,代表一个返回结果的任务,并且有一个call()方法。在这里,我们使用lambda表达式创建了它的一个实例。

Creating an instance of Callable doesn’t take us anywhere; we still have to pass this instance to an executor that will take care of starting the task in a new thread, and give us back the valuable Future object. That’s where ExecutorService comes in.

创建一个Callable的实例并没有给我们带来任何好处;我们仍然必须将这个实例传递给一个执行者,该执行者将负责在一个新的线程中启动任务,并将有价值的Future对象还给我们。这就是ExecutorService的作用。

There are a few ways we can access an ExecutorService instance, and most of them are provided by the utility class Executors static factory methods. In this example, we used the basic newSingleThreadExecutor(), which gives us an ExecutorService capable of handling a single thread at a time.

我们有几种方法可以访问ExecutorService实例,其中大部分是由实用类Executors静态工厂方法提供。在这个例子中,我们使用了基本的newSingleThreadExecutor(),它给了我们一个ExecutorService,能够一次处理一个单线程。

Once we have an ExecutorService object, we just need to call submit(), passing our Callable as an argument. Then submit() will start the task and return a FutureTask object, which is an implementation of the Future interface.

一旦我们有了ExecutorService对象,我们只需调用submit(),将我们的Callable作为一个参数。然后submit()将启动任务并返回一个FutureTask对象,它是Future接口的一个实现。

3. Consuming Futures

3.消费期货

Up to this point, we’ve learned how to create an instance of Future.

到此为止,我们已经学会了如何创建一个Future的实例。

In this section, we’ll learn how to work with this instance by exploring all the methods that are part of Future‘s API.

在本节中,我们将通过探索作为Future的API一部分的所有方法来学习如何使用这个实例。

3.1. Using isDone() and get() to Obtain Results

3.1.使用isDone()get()来获取结果

Now we need to call calculate(), and use the returned Future to get the resulting Integer. Two methods from the Future API will help us with this task.

现在我们需要调用calculate(),并使用返回的Future来获取结果Integer。来自Future API的两个方法将帮助我们完成这项任务。

Future.isDone() tells us if the executor has finished processing the task. If the task is complete, it will return true; otherwise, it returns false.

Future.isDone()告诉我们执行器是否已经完成了任务的处理。如果任务已经完成,它将返回true;否则,它将返回false

The method that returns the actual result from the calculation is Future.get(). We can see that this method blocks the execution until the task is complete. However, this won’t be an issue in our example because we’ll check if the task is complete by calling isDone().

返回计算的实际结果的方法是 Future.get()。我们可以看到,这个方法会阻止执行,直到任务完成。然而,在我们的例子中,这不会是一个问题,因为我们将通过调用isDone()来检查任务是否已经完成。

By using these two methods, we can run other code while we wait for the main task to finish:

通过使用这两种方法,我们可以在等待主任务完成时运行其他代码。

Future<Integer> future = new SquareCalculator().calculate(10);

while(!future.isDone()) {
    System.out.println("Calculating...");
    Thread.sleep(300);
}

Integer result = future.get();

In this example, we’ll write a simple message on the output to let the user know the program is performing the calculation.

在这个例子中,我们将在输出端写一个简单的信息,让用户知道程序正在进行计算。

The method get() will block the execution until the task is complete. Again, this won’t be an issue because in our example, get() will only be called after making sure that the task is finished. So in this scenario, future.get() will always return immediately.

方法get()将阻止执行,直到任务完成。同样,这不会是一个问题,因为在我们的例子中,get()将只在确保任务完成后被调用。所以在这种情况下,future.get()将总是立即返回。

It’s worth mentioning that get() has an overloaded version that takes a timeout and a TimeUnit as arguments:

值得一提的是,get()有一个重载版本,它接受一个超时和一个TimeUnit作为参数。

Integer result = future.get(500, TimeUnit.MILLISECONDS);

The difference between get(long, TimeUnit) and get() is that the former will throw a TimeoutException if the task doesn’t return before the specified timeout period.

get(long, TimeUnit)get()的区别在于,如果任务没有在指定的超时时间内返回,前者会抛出TimeoutException

3.2. Canceling a Future With cancel()

3.2.用cancel()取消一个未来

Suppose we triggered a task, but for some reason, we don’t care about the result anymore. We can use Future.cancel(boolean) to tell the executor to stop the operation and interrupt its underlying thread:

假设我们触发了一个任务,但由于某种原因,我们不再关心其结果了。我们可以使用Future.cancel(boolean)来告诉执行器停止操作并中断其底层线程。

Future<Integer> future = new SquareCalculator().calculate(4);

boolean canceled = future.cancel(true);

Our instance of Future, from the code above, will never complete its operation. In fact, if we try to call get() from that instance, after the call to cancel(), the outcome will be a CancellationException. Future.isCancelled() will tell us if a Future was already cancelled. This can be quite useful to avoid getting a CancellationException.

在上面的代码中,我们的Future的实例,将永远不会完成它的操作。事实上,如果我们在调用cancel()之后,试图从该实例中调用get(),其结果将是一个CancellationExceptionFuture.isCancelled()将告诉我们是否一个Future已经被取消了。这对于避免获得CancellationException来说是相当有用的。

It’s also possible that a call to cancel() fails. In that case, the returned value will be false. It’s important to note that cancel() takes a boolean value as an argument. This controls whether the thread executing the task should be interrupted or not.

也有可能对cancel()的调用失败。在这种情况下,返回值将是false。值得注意的是,cancel()需要一个boolean值作为参数。这可以控制执行任务的线程是否应该被中断。

4. More Multithreading With Thread Pools

4.使用线程池的更多多线程

Our current ExecutorService is single threaded, since it was obtained with the Executors.newSingleThreadExecutor. To highlight this single thread, let’s trigger two calculations simultaneously:

我们当前的ExecutorService是单线程的,因为它是通过Executors.newSingleThreadExecutor获得的。为了突出这个单线程,让我们同时触发两个计算。

SquareCalculator squareCalculator = new SquareCalculator();

Future<Integer> future1 = squareCalculator.calculate(10);
Future<Integer> future2 = squareCalculator.calculate(100);

while (!(future1.isDone() && future2.isDone())) {
    System.out.println(
      String.format(
        "future1 is %s and future2 is %s", 
        future1.isDone() ? "done" : "not done", 
        future2.isDone() ? "done" : "not done"
      )
    );
    Thread.sleep(300);
}

Integer result1 = future1.get();
Integer result2 = future2.get();

System.out.println(result1 + " and " + result2);

squareCalculator.shutdown();

Now let’s analyze the output for this code:

现在我们来分析一下这段代码的输出。

calculating square for: 10
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
calculating square for: 100
future1 is done and future2 is not done
future1 is done and future2 is not done
future1 is done and future2 is not done
100 and 10000

It’s clear that the process isn’t parallel. We can see that the second task only starts once the first task is complete, making the whole process take around 2 seconds to finish.

很明显,这个过程并不平行。我们可以看到,第二个任务只有在第一个任务完成后才开始,这使得整个过程需要2秒左右才能完成。

To make our program really multi-threaded, we should use a different flavor of ExecutorService. Let’s see how the behavior of our example changes if we use a thread pool provided by the factory method Executors.newFixedThreadPool():

为了使我们的程序真正成为多线程,我们应该使用不同风味的ExecutorService。让我们看看如果我们使用由工厂方法Executors.newFixedThreadPool()提供的线程池,我们的例子的行为会有什么变化。

public class SquareCalculator {
 
    private ExecutorService executor = Executors.newFixedThreadPool(2);
    
    //...
}

With a simple change in our SquareCalculator class, we now have an executor which is able to use 2 simultaneous threads.

通过对SquareCalculator类的简单修改,我们现在有了一个能够同时使用两个线程的执行器。

If we run the exact same client code again, we’ll get the following output:

如果我们再次运行完全相同的客户端代码,我们会得到以下输出。

calculating square for: 10
calculating square for: 100
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
100 and 10000

This is looking much better now. We can see that the 2 tasks start and finish running simultaneously, and the whole process takes around 1 second to complete.

现在看起来好多了。我们可以看到,2个任务同时开始和结束运行,整个过程大约需要1秒钟完成。

There are other factory methods that can be used to create thread pools, like Executors.newCachedThreadPool(), which reuses previously used Threads when they’re available, and Executors.newScheduledThreadPool(), which schedules commands to run after a given delay.

还有其他工厂方法可用于创建线程池,比如Executors.newCachedThreadPool()当先前使用的Threads可用时,它可以重用它们,以及Executors.newScheduledThreadPool()它可以安排命令在指定延迟后运行

For more information about ExecutorService, read our article dedicated to the subject.

有关ExecutorService的更多信息,请阅读我们专门针对该主题的文章

5. Overview of ForkJoinTask

5.ForkJoinTask的概述

ForkJoinTask is an abstract class which implements Future, and is capable of running a large number of tasks hosted by a small number of actual threads in ForkJoinPool.

ForkJoinTask是一个抽象类,它实现了Future,并能够运行大量的任务,这些任务由ForkJoinPool中的少量实际线程托管。

In this section, we’ll quickly cover the main characteristics of ForkJoinPool. For a comprehensive guide about the topic, check out our Guide to the Fork/Join Framework in Java.

在本节中,我们将快速介绍ForkJoinPool的主要特征。有关该主题的全面指南,请查看我们的Java中的Fork/Join框架指南

The main characteristic of a ForkJoinTask is that it will usually spawn new subtasks as part of the work required to complete its main task. It generates new tasks by calling fork(), and it gathers all results with join(), thus the name of the class.

ForkJoinTask的主要特征是,它通常会产生新的子任务,作为完成其主要任务所需工作的一部分。它通过调用fork()来生成新的任务,并通过join()来收集所有结果,这就是该类的名称。

There are two abstract classes that implement ForkJoinTask: RecursiveTask, which returns a value upon completion, and RecursiveAction, which doesn’t return anything. As their names imply, these classes are to be used for recursive tasks, such as file-system navigation or complex mathematical computation.

有两个抽象类实现了ForkJoinTask递归任务,,完成后返回一个值;递归行动,,不返回任何东西。正如它们的名字所暗示的,这些类将被用于递归任务,例如文件系统导航或复杂的数学计算。

Let’s expand our previous example to create a class that, given an Integer, will calculate the sum squares for all of its factorial elements. So for instance, if we pass the number 4 to our calculator, we should get the result from the sum of 4² + 3² + 2² + 1², which is 30.

让我们扩展之前的例子,创建一个类,给定一个Integer,将计算其所有阶乘元素的和的平方。因此,例如,如果我们将数字4传给我们的计算器,我们应该得到4²+3²+2²+1²之和的结果,即30。

First, we need to create a concrete implementation of RecursiveTask and implement its compute() method. This is where we’ll write our business logic:

首先,我们需要创建一个RecursiveTask的具体实现,并实现其compute() 方法。这就是我们要编写业务逻辑的地方。

public class FactorialSquareCalculator extends RecursiveTask<Integer> {
 
    private Integer n;

    public FactorialSquareCalculator(Integer n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n <= 1) {
            return n;
        }

        FactorialSquareCalculator calculator 
          = new FactorialSquareCalculator(n - 1);

        calculator.fork();

        return n * n + calculator.join();
    }
}

Notice how we achieve recursiveness by creating a new instance of FactorialSquareCalculator within compute(). By calling fork(), a non-blocking method, we ask ForkJoinPool to initiate the execution of this subtask.

请注意我们是如何通过在compute()中创建FactorialSquareCalculator的新实例来实现递归性的。通过调用fork()(一个非阻塞的方法),我们要求ForkJoinPool启动这个子任务的执行。

The join() method will return the result from that calculation, to which we’ll add the square of the number we’re currently visiting.

join()方法将返回该计算的结果,我们将在其中加入我们目前正在访问的数字的平方。

Now we just need to create a ForkJoinPool to handle the execution and thread management:

现在我们只需要创建一个ForkJoinPool来处理执行和线程管理。

ForkJoinPool forkJoinPool = new ForkJoinPool();

FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);

forkJoinPool.execute(calculator);

6. Conclusion

6.结论

In this article, we comprehensively explored the Future interface, touching on all of its methods. We also learned how to leverage the power of thread pools to trigger multiple parallel operations. The main methods from the ForkJoinTask class, fork() and join(), were briefly covered as well.

在这篇文章中,我们全面地探讨了Future接口,涉及到它的所有方法。我们还学习了如何利用线程池的力量来触发多个并行操作。我们还简要介绍了ForkJoinTask类中的主要方法:fork()join()

We have many other great articles on parallel and asynchronous operations in Java. Here are three of them that are closely related to the Future interface, some of which are already mentioned in the article:

我们还有很多关于Java中的并行和异步操作的优秀文章。下面是其中三篇与Future接口密切相关的文章,其中一些已经在文章中提到。

As always, the source code used in this article can be found in our GitHub repository.

一如既往,本文中使用的源代码可以在我们的GitHub库中找到。