java如何实现一个Future

实现Futrue接口
public class MsgFuture<V> implements java.util.concurrent.Future<V> {
...
...
}
Future的主要特性为Future.get()、
get()
get(long timeout, TimeUnit unit)
主要思路如下:
构造MsgFuture时,设置开始时间,这里是sendTime;设置timeout,默认get()方法的超时时间,我们的程序不可能会无限等待
默认的get()对应的值域是result,默认为一个NULL对象,标识没有返回数据
result的值需要其他线程在做完任务后将值写到Future对象中,这里暴露了一个方法setResult(object)
/**
* 设置结果值result,唤醒condition {@link #get(long, TimeUnit)}
* @param result
*/
public synchronized void setResult(Object result) {
reentrantLock.lock();
try {
this.result = result;
condition.signalAll();
}finally {
reentrantLock.unlock();
} }
使用ReentrantLock来进行数据可见性控制
condition.signalAll()可以唤醒condition.await的阻塞wait
至于其他线程如何调用到setResult(object)方法,可以使用ConcurrentHashMap,key为msgId,值为MsgFuture对象,设置成一个全局的,或两个线程都可访问,其他线程根据msgId获取到MsgFuture,然后调用setResult(object)方法
/**
* 获取结果,如果到达timeout还未得到结果,则会抛出TimeoutException
* @param timeout
* @param unit
* @return
* @throws InterruptedException
* @throws TimeoutException
*/
@SuppressWarnings("all")
public V get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
long left = getLeftTime(timeout, unit); //根据timeout配置获取剩余的世界
if(left < 0){
//已经没有剩余时间
if(isDone()){ //如果已经完成,直接放回结果
return (V)this.result;
}else{
//timeout
throw new TimeoutException("返回超时,后续的响应将会被丢弃abort");
}
}else{ reentrantLock.lock(); //同步
try {
//获取锁后先判断是否已经完成,防止无意义的await
if(isDone()){ //先判断是否已经完成
return (V)this.result; //直接返回
}
logger.debug("await "+left+" ms");
condition.await(getLeftTime(timeout, unit), TimeUnit.MILLISECONDS); //没有返回,阻塞等待,如果condition被唤醒,也会提前退出
}finally {
reentrantLock.unlock();
}
if(isDone()){ //被唤醒或超时时间已到,尝试判断是否完成
return (V)this.result; //返回
} throw new TimeoutException("未获取到结果"); //超时
}
}
public boolean isDone() {
return this.result != NULL;
}
全部代码
public class MsgFuture<V> implements java.util.concurrent.Future<V> {
private final static Logger logger = LoggerFactory.getLogger(MsgFuture.class);
/**
* 全局的空对象,如果Future获取到值了,那么一定不是NULL
*/
private final static Object NULL = new Object();
/**
* 主锁
*/
private final ReentrantLock reentrantLock = new ReentrantLock();
/**
* 条件,利用它的condition.await(left, TimeUnit.MILLISECONDS)和notifyAll方法来实现阻塞、唤醒
*/
private final Condition condition = reentrantLock.newCondition();
private int timeout;
private volatile Object result = NULL;
private long sendTime;
public MsgFuture(int timeout, long sendTime) {
this.timeout = timeout;
this.sendTime = sendTime;
}
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return this.result != NULL;
}
/**
* 获取future结果
* @return
* @throws InterruptedException
*/
public V get() throws InterruptedException {
logger.debug("sendTime:{}",sendTime);
try {
return get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
logger.error("获取future结果异常", e);
}
return null;
}
/**
* 获取结果,如果到达timeout还未得到结果,则会抛出TimeoutException
* @param timeout
* @param unit
* @return
* @throws InterruptedException
* @throws TimeoutException
*/
@SuppressWarnings("all")
public V get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
long left = getLeftTime(timeout, unit);
if(left < 0){
//已经没有剩余时间
if(isDone()){
return (V)this.result;
}else{
//timeout
throw new TimeoutException("返回超时,后续的响应将会被丢弃abort");
}
}else{
reentrantLock.lock();
try {
//获取锁后先判断是否已经完成,防止无意义的await
if(isDone()){
return (V)this.result;
}
logger.debug("await "+left+" ms");
condition.await(getLeftTime(timeout, unit), TimeUnit.MILLISECONDS);
}finally {
reentrantLock.unlock();
}
if(isDone()){
return (V)this.result;
}
throw new TimeoutException("未获取到结果");
}
}
/**
* 设置结果值result,唤醒condition {@link #get(long, TimeUnit)}
* @param result
*/
public synchronized void setResult(Object result) {
reentrantLock.lock();
try {
this.result = result;
condition.signalAll();
}finally {
reentrantLock.unlock();
}
}
/**
* 计算剩余时间
* @param timeout
* @param unit
* @return
*/
private long getLeftTime(long timeout, TimeUnit unit){
long now = System.currentTimeMillis();
timeout = unit.toMillis(timeout); // 转为毫秒
return timeout - (now - sendTime);
}
/*public static void main(String[] args) {
MsgFuture msgFuture = new MsgFuture(2000,System.currentTimeMillis());
//测试先唤醒、后get是否正常
msgFuture.setResult("yoxi");
try {
System.out.println(msgFuture.get(2000,TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
logger.error("Interrupt异常", e);
} catch (TimeoutException e) {
logger.error("测试先唤醒,后get出错", e);
}
}*/
}
java如何实现一个Future的更多相关文章
- java多线程之Future和FutureTask
Executor框架使用Runnable 作为其基本的任务表示形式.Runnable是一种有局限性的抽象,然后可以写入日志,或者共享的数据结构,但是他不能返回一个值. 许多任务实际上都是存在延迟计算的 ...
- Java多线程编程中Future模式的详解
Java多线程编程中,常用的多线程设计模式包括:Future模式.Master-Worker模式.Guarded Suspeionsion模式.不变模式和生产者-消费者模式等.这篇文章主要讲述Futu ...
- Java多线程编程中Future模式的详解<转>
Java多线程编程中,常用的多线程设计模式包括:Future模式.Master-Worker模式.Guarded Suspeionsion模式.不变模式和生产者-消费者模式等.这篇文章主要讲述Futu ...
- Java 并发编程——Callable+Future+FutureTask
Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...
- 使用executor、callable以及一个Future 计算欧拉数e
package test; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMo ...
- 用Java语言编写一个简易画板
讲了三篇概博客的概念,今天,我们来一点实际的东西.我们来探讨一下如何用Java语言,编写一块简易的画图板. 一.需求分析 无论我们使用什么语言,去编写一个什么样的项目,我们的第一步,总是去分析这个项目 ...
- 如何在JAVA中实现一个固定最大size的hashMap
如何在JAVA中实现一个固定最大size的hashMap 利用LinkedHashMap的removeEldestEntry方法,重载此方法使得这个map可以增长到最大size,之后每插入一条新的记录 ...
- 利用java实现的一个发送手机短信的小例子
今天闲来无事,在微博上看到一个关于用java实现的一个发送手机短信的程序,看了看,写的不太相信,闲的没事,把他整理下来,以后可能用得着 JAVA发送手机短信,流传有几种方法:(1)使用webservi ...
- 教你如何使用Java手写一个基于链表的队列
在上一篇博客[教你如何使用Java手写一个基于数组的队列]中已经介绍了队列,以及Java语言中对队列的实现,对队列不是很了解的可以我上一篇文章.那么,现在就直接进入主题吧. 这篇博客主要讲解的是如何使 ...
随机推荐
- 实验 3:Mininet 实验——测量路径的损耗率
实验目的 在实验 2 的基础上进一步熟悉 Mininet 自定义拓扑脚本,以及与损耗率相关的设 定:初步了解 Mininet 安装时自带的 POX 控制器脚本编写,测试路径损耗率. 实验任务 h0 向 ...
- 快速上手spring
一.初始程序 1.在父类pom导入所需要的jar包 2.编写一个实体类 3.创建一个beans.xml,创建一个bean即创建一个user对象,可在bean内配置property即设置属性值 4.用测 ...
- Mac更换鼠标指针样式_mousecape教程
mousecape项目介绍 这是github上的一个项目,作者是alexzielenski. 项目是用于修改Mac系统鼠标样式的,支持动态鼠标样式. 该项目停止更新于2014年,目前仍可以被较新的系统 ...
- brew清华镜像
https://mirror.tuna.tsinghua.edu.cn/help/homebrew/
- Redis报错“ OOM command not allowed when used memory > 'maxmemory' ”
生产环境上遇到这个问题,控制台不停打印 "OOM command not allowed when used memory > 'maxmemory' "; 起初不知道是什么 ...
- python学习笔记1之-python简介及其环境安装
python学习笔记之-python简介及其环境安装 最近几年python之火不用多说,最近开始利用时间自学python,在学习的过程中,按照自己的思路和理解记录下学习的过程,并分享出来,如果正好你也 ...
- Leetcode-二分
69. x的平方根 https://leetcode-cn.com/problems/sqrtx/ 实现 int sqrt(int x) 函数. 计算并返回 x 的平方根,其中 x 是非负整数. 由于 ...
- Python实现的数据结构与算法之双端队列详解
一.概述 双端队列(deque,全名double-ended queue)是一种具有队列和栈性质的线性数据结构.双端队列也拥有两端:队首(front).队尾(rear),但与队列不同的是,插入操作在两 ...
- 【题解】CF413C Jeopardy!
\(\color{blue}{Link}\) \(\text{Solution:}\) 首先,显然的策略是把一定不能翻倍的先加进来.继续考虑下一步操作. 考虑\(x,y\)两个可以翻倍的物品,且\(a ...
- mysql linux 命令行操作
1. 登录mysql mysql -u 用户名 -p 回车输入密码