美文网首页
创建Future时加synchronized关键字

创建Future时加synchronized关键字

作者: 找不到工作的_Ngone | 来源:发表于2018-04-24 22:17 被阅读0次

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

  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中的情形,但是在其它的异步代码执行时,应该也遵循同样的原理。

相关文章

网友评论

      本文标题:创建Future时加synchronized关键字

      本文链接:https://www.haomeiwen.com/subject/qydslftx.html