参考文档:https://www.cnblogs.com/cz123/p/7693064.html

一、为什么要使用Future?

先上一个场景:假如你突然想做饭,但是没有厨具,也没有食材。网上购买厨具比较方便,食材去超市买更放心。

实现分析:在快递员送厨具的期间,我们肯定不会闲着,可以去超市买食材。所以,在主线程里面另起一个子线程去网购厨具。

但是,子线程执行的结果是要返回厨具的,而run方法是没有返回值的。所以,这才是难点,需要好好考虑一下。

模拟代码1:

public class CommonCook {

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        // 第一步 网购厨具
        OnlineShopping thread = new OnlineShopping();
        thread.start();
        thread.join();  // 保证厨具送到
        // 第二步 去超市购买食材
        Thread.sleep(2000);  // 模拟购买食材时间
        Shicai shicai = new Shicai();
        System.out.println("第二步:食材到位");
        // 第三步 用厨具烹饪食材
        System.out.println("第三步:开始展现厨艺");
        cook(thread.chuju, shicai);
        
        System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
    }
    
    // 网购厨具线程
    static class OnlineShopping extends Thread {
        
        private Chuju chuju;

        @Override
        public void run() {
            System.out.println("第一步:下单");
            System.out.println("第一步:等待送货");
            try {
                Thread.sleep(5000);  // 模拟送货时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第一步:快递送到");
            chuju = new Chuju();
        }
        
    }

    //  用厨具烹饪食材
    static void cook(Chuju chuju, Shicai shicai) {}
    
    // 厨具类
    static class Chuju {}
    
    // 食材类
    static class Shicai {}
} 

运行结果:

第一步:下单
第一步:等待送货
第一步:快递送到
第二步:食材到位
第三步:开始展现厨艺
总共用时7023ms

可以看到,多线程已经失去了意义。在厨具送到期间,我们不能干任何事。对应代码,就是调用join方法阻塞主线程。

有人问了,不阻塞主线程行不行???不行!!!

从代码来看的话,run方法不执行完,属性chuju就没有被赋值,还是null。换句话说,没有厨具,怎么做饭。

Java现在的多线程机制,核心方法run是没有返回值的;如果要保存run方法里面的计算结果,必须等待run方法计算完,无论计算过程多么耗时

面对这种尴尬的处境,程序员就会想:在子线程run方法计算的期间,能不能在主线程里面继续异步执行

这种想法的核心就是Future模式,下面先应用一下Java自己实现的Future模式。

模拟代码2:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureCook {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long startTime = System.currentTimeMillis();
        // 第一步 网购厨具
        Callable<Chuju> onlineShopping = new Callable<Chuju>() {

            @Override
            public Chuju call() throws Exception {
                System.out.println("第一步:下单");
                System.out.println("第一步:等待送货");
                Thread.sleep(5000);  // 模拟送货时间
                System.out.println("第一步:快递送到");
                return new Chuju();
            }

        };
        FutureTask<Chuju> task = new FutureTask<Chuju>(onlineShopping); // 将Callable封装到FutureTask
        new Thread(task).start();
        // 第二步 去超市购买食材
        Thread.sleep(2000);  // 模拟购买食材时间
        Shicai shicai = new Shicai();
        System.out.println("第二步:食材到位");
        // 第三步 用厨具烹饪食材
        if (!task.isDone()) {  // 联系快递员,询问是否到货
            System.out.println("第三步:厨具还没到,心情好就等着(心情不好就调用cancel方法取消订单)");
        }
        Chuju chuju = task.get();
        System.out.println("第三步:厨具到位,开始展现厨艺");
        cook(chuju, shicai);

        System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
    }

    //  用厨具烹饪食材
    static void cook(Chuju chuju, Shicai shicai) {}

    // 厨具类
    static class Chuju {}

    // 食材类
    static class Shicai {}

}

运行结果:

第一步:下单
第一步:等待送货
第二步:食材到位
第三步:厨具还没到,心情好就等着(心情不好就调用cancel方法取消订单)
第一步:快递送到
第三步:厨具到位,开始展现厨艺
总共用时5015ms

可以看见,在快递员送厨具的期间,我们没有闲着,可以去买食材;而且我们知道厨具到没到,甚至可以在厨具没到的时候,取消订单不要了。

下面具体分析一下第二段代码:

1)把耗时的网购厨具逻辑,封装到了一个Callable的call方法里面(即开启一个线程异步执行)。

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Callable接口可以看作是Runnable接口的补充,call方法带有返回值,并且可以抛出异常。

2)把Callable实例当作参数,生成一个FutureTask的对象,然后把这个对象当作一个Runnable,作为参数另起线程。

将Callable封装到FutureTask

public class FutureTask<V> implements RunnableFuture<V> {

FutureTask实现Runnable接口

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

其中

public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

Future接口有如下方法:

public interface Future<V> {
    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

这个继承体系中的核心接口是Future。Future的核心思想是:一个方法f,计算过程可能非常耗时,等待f返回,显然不明智。可以在调用f的时候,立马返回一个Future,可以通过Future这个数据结构去控制方法f的计算过程

get方法:获取计算结果(如果还没计算完,也是必须等待的)
cancel方法:还没计算完,可以取消计算过程
isDone方法:判断是否计算完
isCancelled方法:判断计算是否被取消

这些接口的设计很完美,FutureTask的实现注定不会简单,后面再说。

3)在第三步里面,调用了isDone方法查看状态,然后直接调用task.get方法获取厨具,不过这时还没送到,所以还是会等待3秒。对比第一段代码的执行结果,这里我们节省了2秒。这是因为在快递员送货期间,我们去超市购买食材,这两件事在同一时间段内异步执行。

通过以上3步,我们就完成了对Java原生Future模式最基本的应用。

二、Future模式衍生出来的更高级的应用

再上一个场景:我们自己写一个简单的数据库连接池,能够复用数据库连接,并且能在高并发情况下正常工作。

实现代码1:

import java.util.concurrent.ConcurrentHashMap;

public class ConnectionPool {

    private ConcurrentHashMap<String, Connection> pool = new ConcurrentHashMap<String, Connection>();

    public Connection getConnection(String key) {
        Connection conn = null;
        if (pool.containsKey(key)) {
            conn = pool.get(key);
        } else {
            conn = createConnection();
            pool.putIfAbsent(key, conn);
        }
        return conn;
    }

    public Connection createConnection() {
        return new Connection();
    }

    class Connection {}
}

 我们用了ConcurrentHashMap,这样就不必把getConnection方法置为synchronized(当然也可以用Lock),当多个线程同时调用getConnection方法时,性能大幅提升。

貌似很完美了,但是有可能导致多余连接的创建,推演一遍:

某一时刻,同时有3个线程进入getConnection方法,调用pool.containsKey(key)都返回false,然后3个线程各自都创建了连接。虽然ConcurrentHashMap的put方法只会加入其中一个,但还是生成了2个多余的连接。如果是真正的数据库连接,那会造成极大的资源浪费。

所以,我们现在的难点是:如何在多线程访问getConnection方法时,只执行一次createConnection。

结合之前Future模式的实现分析:当3个线程都要创建连接的时候,如果只有一个线程执行createConnection方法创建一个连接,其它2个线程只需要用这个连接就行了。再延伸,把createConnection方法放到一个Callable的call方法里面,然后生成FutureTask。我们只需要让一个线程执行FutureTask的run方法,其它的线程只执行get方法就好了。

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ConnectionPool {
   private ConcurrentHashMap<String, FutureTask<Connection>> pool = new ConcurrentHashMap<String, FutureTask<Connection>>();
    public Connection getConnection(String key) throws InterruptedException, ExecutionException {
        FutureTask<Connection> connectionTask = pool.get(key);
        if (connectionTask != null) {
            return connectionTask.get();
        } else {
            Callable<Connection> callable = new Callable<Connection>() {
                @Override
                public Connection call() throws Exception {
                    return createConnection();
                }
            };
            FutureTask<Connection> newTask = new FutureTask<Connection>(callable);
            connectionTask = pool.putIfAbsent(key, newTask); // 虽然三个线程都创建了FutureTask,但是只有一个放入ConcurrentHashMap
            if (connectionTask == null) {
                connectionTask = newTask;
                connectionTask.run(); // 异步创建链接
            }
            return connectionTask.get(); // 等待链接创建完成
        }
    }

    public Connection createConnection() {
        return new Connection();
    }

    class Connection {
    }
}

 推演一遍:当3个线程同时进入else语句块时,各自都创建了一个FutureTask,但是ConcurrentHashMap只会加入其中一个。第一个线程执行pool.putIfAbsent方法后返回null,然后connectionTask被赋值,接着就执行run方法去创建连接,最后get。后面的线程执行pool.putIfAbsent方法不会返回null,就只会执行get方法。

putIfAbsent方法:当指定的key没有映射值,则与给定的值进行映射,并返回null,否则返回当前值。

    public V putIfAbsent(K key, V value) {
        return putVal(key, value, true);
    }

FutureTask的run()方法

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

在并发的环境下,通过FutureTask作为中间转换,成功实现了让某个方法只被一个线程执行

三、项目实战

1、案例1:根据异步调用返回的结果再发起Http请求

controller

@RestController
@RequestMapping("/proexpaired")
public class MedicineExpWarnSchedulerController {
    @Resource
    private MedicineExpWarnAsync medicineExpWarnAsync;

    /**
     * 药品过期预警数据写入数据库
     *
     * @return
     */
    @PostMapping("/save")
    public RetResult saveMedicineExpWarnData(@RequestBody Data4Rest data4Rest) throws ExecutionException, InterruptedException {
        Future<String> future = medicineExpWarnAsync.saveMedicineExpWarnData(data4Rest.getPostdata());
        medicineExpWarnAsync.callBack(future,data4Rest);
        return RetResponse.makeOKRsp("收到任务");
    }
}

service

@EnableConfigurationProperties(PlatformUrlProperties.class)
@Component
public class MedicineExpWarnAsync {
    @Resource
    private MedicineExpWarnComponent component;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private PlatformUrlProperties platformUrlProperties;

    @Async
    public Future<String> saveMedicineExpWarnData(Map<String,String> postData) {
        String retResult = component.saveMedicineExpWarn(platformUrlProperties.getAppKey2(), platformUrlProperties.getPubKey2(), platformUrlProperties.getMedicineExpWarnUrl(), postData);
        return new AsyncResult(retResult); // 封装成Future
    }

    /**
     * 任务总回调函数
     * @param task
     * @param data4Rest
     */
    @Async  // 必须要用Async异步执行,否则主线程会一直等待callBack方法执行完毕才会返回信息给调用者
    public void callBack(Future<String> task, Data4Rest data4Rest) throws InterruptedException, ExecutionException {
        Data4RestCallback dr = new Data4RestCallback();
        for (;;) { // 注意:这里要加while true死循环,否则isDone()返回false,callBack执行完毕
            if(task.isDone()) { // 如果前面一个方法执行完成,则调用另外一个接口
                System.out.println("任务id:" + data4Rest.getRuleid());
                dr.setCode(1);// 1/成功;0/失败
                dr.setMessage("任务完成" + task.get());
                dr.setRuleid(data4Rest.getRuleid());
                dr.setTasksign(data4Rest.getTasksign());
                restTemplate.postForObject(platformUrlProperties.getTimetaskurl(), dr, DataReturn.class);
                // 任务都调用完成,退出循环等待
                break;
            }
            // 没3秒循环一次,任务的完成需要时间,不要频繁循环
            Thread.sleep(3000);
        }
    }

}

注意:这里一定要用异步,即Async,而且还要用死循环,否则isDone()方法返回false,导致callBack中的代码未执行

其中:AsyncResult实现ListenableFuture接口

public class AsyncResult<V> implements ListenableFuture<V> {

ListenableFuture接口继承Future接口

public interface ListenableFuture<T> extends Future<T> {

2、案例2:根据异步调用返回的结果再修改处理状态是成功还是失败

实现类中部分代码

@Override
    public String scanCodeOutstore(JSONObject jsonObj) throws ExecutionException, InterruptedException {
     ....
        OutstoreUploadLog uploadLog = new OutstoreUploadLog();
        // 记录日志,处理状态为:处理中
        if (StringUtils.isNotBlank(path)) {
            uploadLog = insertUploadLog(xxx);
        }
        // 异步调用
        Future<Long> future = outStoreAsycService.saveOutstoreInfo(uploadLog);
        outStoreAsycService.callBack(future,uploadLog);
        return null;
    }

saveOutstoreInfo方法:该方法异步执行,主要用于控制事务。返回outstoreId是为了判断对数据库的操作是成功还是失败,如果失败,则返回null

    @Async
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED) // 对抛出的任何异常都进行自动回滚
    public Future<Long> saveOutstoreInfo(OutstoreUploadLog uploadLog) {
        Long outstoreId = null;
        try {
            // 所有对数据库进行DML操作的语句
        } catch (Exception e) {
            log.info(e.getMessage());
       // 手动回滚 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } return new AsyncResult(outstoreId); // 封装成Future }

callBack方法:必须异步执行,才可以快速返回结果给调用者。改方法的目的是为了记录日志。

/**
     * 任务总回调函数
     * @param task
     */
    @Async  // 必须要用Async异步执行,否则主线程会一直等待callBack方法执行完毕才会返回信息给调用者
    public void callBack(Future<Long> task,OutstoreUploadLog uploadLog2) throws ExecutionException, InterruptedException {
        for (;;) { // 注意:这里要加while true死循环,否则isDone()返回false,callBack执行完毕
            if(task.isDone()) { // 如果前面一个方法执行完成,则调用另外一个接口
                uploadLog2.setOrderId(task.get());
                uploadLog2.setUpdateTime(new Date());
                if (null == task.get()) { // future的get()方法返回Future中封装的值,如这里的outstoreId
                    // 如果出现异常,则修改处理状态为失败
                    uploadLog2.setDealStatus("3");
                    uploadLog2.setDealDesc("处理失败");
                } else {
                    // 如果上面的都成功了,则修改日志状态未处理成功
                    uploadLog2.setDealStatus("2");
                    uploadLog2.setDealDesc("处理成功");
                }
                outstoreUploadLogService.update(uploadLog2);
                // 任务都调用完成,退出循环等待
                break;
            }
            // 没3秒循环一次,任务的完成需要时间,不要频繁循环
            Thread.sleep(3000);
        }
    }

 

posted on 2022-09-09 12:09  周文豪  阅读(195)  评论(0编辑  收藏  举报