对期货进行排序以避免竞争条件

时间:2017-07-05 00:25:07

标签: scala

在此示例中,我有竞争条件,程序末尾的字符串s应打印@并替换#

object TestFutures extends App {

  var s = "THIS IS A STRING"

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map { 
    seq => seq.map {  i =>
          println("BEFORE ---> " + s)
          if (i == 0)
              s = s.replace ( "T", "@")
          else
              s = s.replace ("I", "#")
          println("AFTER ---> " + s)
        }
  }


  Thread.sleep(5000)
}

但代码打印

BEFORE ---> THIS IS A STRING
BEFORE ---> THIS IS A STRING
AFTER ---> TH#S #S A STR#NG
AFTER ---> TH#S #S A STR#NG

如何避免这种竞争条件?如何更改字符串?

1 个答案:

答案 0 :(得分:1)

避免竞争条件的唯一可靠方法是不具备可变状态。 像这样的东西会起作用:

 val s = "THIS IS A STRING"
 Future
   .sequence(Seq(Future(0), Future(1)))
   .map { 
      _.foldLeft(s) {
        case (s, 0) => s.replaceAll("T", "@")
        case (s, _) => s.replaceAll("I", "#")
     }
   }.andThen { 
     case Success(str) => println("RESULT: " + str)
   }