异步处理获取结果集异步接口Future

Future接口是Concurrent包下的,关于他的解释,源码给的解释是


package java.util.concurrent;

/**
 * A {@code Future} represents the result of an asynchronous
 * computation.  Methods are provided to check if the computation is
 * complete, to wait for its completion, and to retrieve the result of
 * the computation.  The result can only be retrieved using method
 * {@code get} when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * {@code cancel} method.  Additional methods are provided to
 * determine if the task completed normally or was cancelled. Once a
 * computation has completed, the computation cannot be cancelled.
 * If you would like to use a {@code Future} for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return {@code null} as a result of the underlying task.

虽然我也不怎么明白

 

在springboot的使用中,我在

log.debug("伴随数据获取完毕,开始等待伴随站点获取... ...");
        List<Future<String>> futureList1 = new ArrayList<>();
        if (flag){
            for (FollowIMSI followIMSI:newList){
                String fieldStr = StringUtils.join(fields, ",");
                String sql = SqlUtils.getTargetSql(fieldStr,esIndex,followType,followIMSI.getFollowCode(),startTime,endTime);
                log.debug("开始伴随站点获取:"+sql);
                Future<String>  followIMSIFuture = followServiceByAsync.findFollowSiteByGP(sql,followIMSI);
                futureList1.add(followIMSIFuture);
            }
        }
        log.debug("等待标签数据全部获取处理完成... ...");
        for (Future<String> f :futureList1){
            String s = f.get();
        }
        log.debug("伴随站点获取完毕,开始获取标签数据... ...");

在方法findFollowSiteByGP(sql,followIMSI)中,我只是返回一个new AsyncResult<>("");一个空的字符串,就是证明执行完成了....

而在下面对收集了Future结果集的list进行遍历查询,如果能get()到值的话,就说明已经异步已经执行完成,整个for结束,也是所有所有异步都执行完成了....所以认为结果是没有问题的.

但是在后面的处理的时候,发现数据量是有不一致,且时常会卡顿..

后来我经理给改了点东西;

如下:

     for (Future<String> f :futureList1){
            //String s = f.get();
            try{
                while (true){
                    if(f.isDone() && !f.isCancelled()){
                        log.debug("查询线程处理完成... ...");
                        break;
                    }else{
                        Thread.sleep(100);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

 

就是在遍历结果集list的时候,不使用get()方法,而是使用Futurn的isDone()方法和isCanceld()方法来判断线程是否是执行结束..

然后在网上找了点资料,讲到Future接口的get()的方法,

这样的设计一般都约定,当使用 get() 阻塞式访问时,返回后那个任务已经完成了 (不管结果是 isDone() 还是 isCancelled())。

而我们对已经取消的线程进程是不需要的,

所以后面的for循环中是对isDone()&&!isCancled()进行的跳出.

但是Thread.sleep(100);也有点儿硬性条件要求了...所以,有点儿线索,但不是太懂的那种...

望大佬们批评指正.!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值