首先说明同步与异步,阻塞与非阻塞的问题:

Asynchronous vs. Synchronous

A method call is considered synchronous if the caller cannot make progress until the method returns a value or throws an exception. On the other hand, an asynchronous call allows the caller to progress after a finite number of steps, and the completion of the method may be signalled via some additional mechanism (it might be a registered callback, a Future, or a message).

A synchronous API may use blocking to implement synchrony, but this is not a necessity. A very CPU intensive task might give a similar behavior as blocking. In general, it is preferred to use asynchronous APIs, as they guarantee that the system is able to progress.

Non-blocking vs. Blocking

We talk about blocking if the delay of one thread can indefinitely delay some of the other threads. A good example is a resource which can be used exclusively by one thread using mutual exclusion. If a thread holds on to the resource indefinitely (for example accidentally running an infinite loop) other threads waiting on the resource can not progress. In contrast, non-blocking means that no thread is able to indefinitely delay others.

Non-blocking operations are preferred to blocking ones, as the overall progress of the system is not trivially guaranteed when it contains blocking operations.

以上文献摘自akka文档,一个方法之所以被称为同步方法,是因为直到该方法返回某值或者抛出异常,该方法的调用者才能得到结果(make progress)。如果一个异步调用需要通过额外的机制(比如callback,Future,message)。如果一个线程的延迟导致了另一个(一些)线程的延迟,那么久出现了阻塞(blocking)。一个例子就是一个资源被一个线程所独占,那么其他线程需要等待这个线程释放资源才能继续执行。

scala中的FuturePromise都是非阻塞的执行,既可以通过回调函数获取结果,但是也可以通过阻塞的方法串行获取结果。

Future

一个Future会持有一个值,虽然这个值在将来某个时间点才可用。

  1. 如果计算未完成,那么这个Future就未完成。
  2. 如果计算完成(得到结果或者异常),这个Future就完成了。

Future只能被指派一次,一旦Future给定了一个值或异常,它的结果不能修改。

object Main extends App {
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
val f:Future[Int]=Future{
Thread.sleep(100)//模拟某个耗时操作 比如网络请求
println("haha")
10
}
Thread.sleep(1000)
}
//haha

异步方法获取结果

目的获取结果,而不是控制执行过程。

scala提供了onSuccess等回调函数。其签名为:def onComplete[U](f: Try[T] => U)(implicit executor: ExecutionContext): Unit

f.onComplete({
case Success(i) => println(i)
case Failure(e) => e.printStackTrace()
})

以上代码采用偏函数形式,或者:

  f.onComplete(result=>result match {
case Success(i)=>println(i)
case Failure(e)=>e.printStackTrace()
})

还可以注册多个回调:

f.onComplete(result=>result match {
case Success(i)=>println(i)
})
f.onComplete(result=>result match {
case Success(i)=>println(i+20)
})

注:多个回调函数之间并不保证执行顺序

同步方法获取结果

通过Await.result可以同步获取结果,或者超时或者异常。Await.ready等待计算完成,不返回结果。

val r=Await.result(f,Duration.Inf) //Await.result(f,1 seconds)

Promise

除了通过Future.apply创建Future对象,还可以使用Promise.future。如果说Future是一个只读的,值还没计算的占位符。那么Promise就是一个可写的,单次指派的容器。Promise可以通过调用success代表Future成功完成,failure方法抛出异常。或者更抽象的complete

object Main extends App {
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future,Promise}
// import scala.concurrent.duration._
val p=Promise[Int]
val f=p.future
val producer=Future{
p complete Try{
100
}
}
val consumer=Future{
f onComplete{
case Success(i)=>println(i)
case Failure(e)=>e.printStackTrace()
}
}
Thread.sleep(1000)
}

scala-Future和Promise的更多相关文章

  1. [转] Scala Async 库 (Scala future, await, async)

    [From] https://colobu.com/2016/02/15/Scala-Async/ 在我以前的文章中,我介绍了Scala Future and Promise.Future代表一个异步 ...

  2. Scala教程之:Future和Promise

    文章目录 定义返回Future的方法 阻塞方式获取Future的值 非阻塞方式获取Future的值 Future链 flatmap VS map Future.sequence() VS Future ...

  3. Future与Promise

    https://code.csdn.NET/DOC_Scala/chinese_scala_offical_document/file/Futures-and-Promises-cn.md#ancho ...

  4. SDP(13): Scala.Future - far from completion,绝不能用来做甩手掌柜

    在前面几篇关于数据库引擎的讨论里很多的运算函数都返回了scala.Future类型的结果,因为我以为这样就可以很方便的实现了non-blocking效果.无论任何复杂的数据处理操作,只要把它们包在一个 ...

  5. C++之future和promise

    future和promise的作用是在不同线程之间传递数据.使用指针也可以完成数据的传递,但是指针非常危险,因为互斥量不能阻止指针的访问:而且指针的方式传递的数据是固定的,如果更改数据类型,那么还需要 ...

  6. Netty 中的异步编程 Future 和 Promise

    Netty 中大量 I/O 操作都是异步执行,本篇博文来聊聊 Netty 中的异步编程. Java Future 提供的异步模型 JDK 5 引入了 Future 模式.Future 接口是 Java ...

  7. Netty 源码解析(三): Netty 的 Future 和 Promise

    今天是猿灯塔“365篇原创计划”第三篇. 接下来的时间灯塔君持续更新Netty系列一共九篇 Netty 源码解析(一): 开始 Netty 源码解析(二): Netty 的 Channel 当前:Ne ...

  8. Future和Promise

    Future用于获取异步操作的结果,而Promise则比较抽象,无法直接猜测出其功能. Future Future最早来源于JDK的java.util.concurrent.Future,它用于代表异 ...

  9. C++11多线程のfuture,promise,package_task

    一.c++11中可以在调用进程中获取被调进程中的结果,具体用法如下 // threadTest.cpp: 定义控制台应用程序的入口点. // #include "stdafx.h" ...

  10. C++并发编程之std::async(), std::future, std::promise, std::packaged_task

    c++11中增加了线程,使得我们可以非常方便的创建线程,它的基本用法是这样的: void f(int n); std::thread t(f, n + 1); t.join(); 但是线程毕竟是属于比 ...

随机推荐

  1. ligerUI---下拉菜单(menubar)动态显示(从后台获取数据)

    写在前面: ligerui的下拉菜单是有点丑的,这也是没有办法的事........这里主要记录下,如何从后台获取数据进行菜单显示. 有两种方式:1.使用json数组来动态添加  2.字符串拼接.  其 ...

  2. 【Win 10 应用开发】在后台播放视频

    从 1607 (14393)版本开始,MediaPlayer 类就可以在前台与后台之间无缝播放,你不必再考虑前台与后之间的通信,所以从 14393 开始,你就不需要再用 BackgroundMedia ...

  3. 虚拟机创建流程中neutron代码分析(二)

    前言: 当nova服务发送了创建port的restful调用信息之后,在neutron服务中有相应的处理函数来处理调用.根据restful的工作原理,是按照 paste.ini文件中配置好的流程去处理 ...

  4. static,final,包,访问修饰符,内部类

    static 关键字可以修饰成员变量,被static修饰的成员变量归属于类static关键字可以修饰成员方法:被static修饰的成员方法可以直接使用类名调用,也可以通过对象调用,建议使用类名.非静态 ...

  5. Java数据结构和算法(五)——队列

    前面一篇博客我们讲解了并不像数组一样完全作为存储数据功能,而是作为构思算法的辅助工具的数据结构——栈,本篇博客我们介绍另外一个这样的工具——队列.栈是后进先出,而队列刚好相反,是先进先出. 1.队列的 ...

  6. log4net使用注意事项

    1配置Log4net Log4net的配置文件有几种使用方式,这里将配置log4net的部分独立出来,即关于log4net的配置独立成文件log4net.config. 1)写入Mysql log4n ...

  7. 《Linux命令行与shell脚本编程大全》第二十二章 gawk进阶

    gawk是一门功能丰富的编程语言,你可以通过它所提供的各种特性来编写好几程序处理数据. 22.1 使用变量 gawk编程语言支持两种不同类型的变量: 内建变量和自定义变量 22.1.1 内建变量 ga ...

  8. QT之TCP通信

    QT中可以通过TCP协议让服务器和客户端之间行通信.所以下面我就围绕服务器和客户端来写. 这是我么写服务器和客户端的具体流程: A.服务器: 1.创建QTcpServer对象         2.启动 ...

  9. springboot之Jwt验证

    简介 什么是JWT(Json Web Token) jwt是为了在网络应用环境间传递声明而执行的一种基于json的开放标准.该token被设计紧凑且安全的,特别适用于SSO场景. jwt的声明一般被用 ...

  10. zzuli 2130: hipercijevi 链式前向星+BFS+输入输出外挂

    2130: hipercijevi Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 595  Solved: 112 SubmitStatusWeb B ...