创建Future时加synchronized关键字

本文想探讨的问题有两个:

  1. 如果我们在synchronized代码块中创建一个Future会发生什么?
  2. 如果我们在创建Future的代码块中加synchronized又会发生什么?

问题的本质是:

  1. 在同步代码块执行异步执行的代码块会发生什么?
  2. 在异步代码块中执行同步代码块又会发生什么?

为此,我们进行了实验。

首先是第一个问题:

import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success}

object FutureSynchronize {
  def compute(x: Int, y: Int): Int = {
      try {
        x / y
      } catch {
        case e: Exception => throw e
      }
  }

  def getFuture(x: Int, y: Int): Future[Int] = {
    synchronized {
      println(Thread.currentThread().getName + " get into synchronized")
      println("we are sleeping, do not bother us.")
      // Thread-0 will stuck on synchronized until Thread-main wake up.
      Thread.sleep(5000)
      val f = Future {
        Thread.sleep(5000)
        compute(x, y)
      }
      f.onComplete {
        case Success(result) => println("Then, print future result: " +  result)
        case Failure(e) => println("Then, rint future exception: " + e)
      }
      println("return a Future without value")
      f
    }
  }
  def main(args: Array[String]): Unit = {
    // Thread-main
    val f1: Future[Int] = getFuture(5, 2)

    var f2: Future[Int] = null
    // Thread-0
    new Thread(new Runnable {
      override def run(): Unit = {
        f2 = getFuture(6000, 200)
     }
    }).start()

    Await.ready(f1, Duration.Inf)
    Await.ready(f2, Duration.Inf)
  }
}

实验证明,当我们在synchronized代码块中创建Future(以及定义onComplete函数)时,如果Thread-main先进入了synchronized代码块,Thread-0就会阻塞在synchronized处。但是,Future在创建完成之后还是会立即(不带结果)返回。同时,虽然在synchronized代码块中定义了onComplete函数,但是也不会立即执行。等到Future异步的计算完成,执行onComplete时,此时线程已经不在synchronized代码块内部了。

第二个问题:

package concurrent


import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success}


object FutureSynchronize {
  def compute(x: Int, y: Int): Int = {
      try {
        x / y
      } catch {
        case e: Exception => throw e
      }
  }

  def getFuture(x: Int, y: Int): Future[Int] = {
    val f = Future {
      synchronized {
        println(Thread.currentThread().getName + " get into       synchronized")
        Thread.sleep(5000)
        compute(x, y)
       }
     }
     f.onComplete {
        case Success(result) => println("Then, print future result: " +  result)
        case Failure(e) => println("Then, rint future exception: " + e)
      }
      println("return a Future without value")
      f
  }

  def main(args: Array[String]): Unit = {
    // Thread-main
    val f1: Future[Int] = getFuture(5, 2)

    var f2: Future[Int] = null
    // Thread-0
    new Thread(new Runnable {
      override def run(): Unit = {
        f2 = getFuture(6000, 200)
      }
    }).start()

    Await.ready(f1, Duration.Inf)
    Await.ready(f2, Duration.Inf)
  }
}

实验证明,如果我们在创建Future的代码块内部加synchronized关键字,执行的效果和不加是一样的。这是因为在scala中,Future执行异步计算时的线程是由ExecutionContextImpl默认从线程池分配的。所以,在这里其实是在两个不同的线程内部各自加锁,所以不存在锁的竞争。当然,如果我们自定义了一个ExecutionContext, 且该ExecutionContext中只有一个可分配的线程,则会发生锁的竞争。则此时,只有当一个Future计算完成时,才能再计算下一个Future。在这里,我们讨论的是scala中的情形,但是在其它的异步代码执行时,应该也遵循同样的原理。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 冒险精神,是每个人类写在基因里的数据。但长久的动乱与不安,让我们更容易偏安一隅。而在冒险与安全之间,安全占80%,...
    玲珑小巫阅读 262评论 0 0
  • 今天孩子们考完试在本班召开了家长会!因想着农村家长忙,不怎么重视家长会,所以我们班一年就召开一次!今天的家长会几个...
    汤汤人阅读 469评论 0 0
  • 01 “我真的受够了在大学里面当一个失败者了,我真的觉得这样的生活还有什么意义呢?为什么我努力了这么多最后还是比不...
    伏澄橙子阅读 283评论 0 3
  • 今天打开简书,发现有好多文章都在写关于2016与2017的话题,想着自从注册简书以来,一直都在充当读者的角色,新的...
    冰雪莲阅读 152评论 0 2