diff --git a/src/main/scala/org/learningconcurrency/exercises/ch2/ex3.scala b/src/main/scala/org/learningconcurrency/exercises/ch2/ex3.scala index a0065c5..04c741a 100644 --- a/src/main/scala/org/learningconcurrency/exercises/ch2/ex3.scala +++ b/src/main/scala/org/learningconcurrency/exercises/ch2/ex3.scala @@ -5,29 +5,14 @@ package ch2 object Ex3 extends App { class SyncVar[T] { - - private var empty:Boolean = true - - private var x:T = null.asInstanceOf[T] + private var state: Option[T] = None def get(): T = this.synchronized { - if (empty) throw new Exception("must be non-empty") - else { - empty = true - val v = x - x = null.asInstanceOf[T] - v - } + state.fold(throw new Exception("No value"))(identity) } - - def put(x: T):Unit = this.synchronized { - if (!empty) throw new Exception("must be empty") - else { - empty = false - this.x = x - } + def put(x: T): Unit = this.synchronized { + state.fold{state = Some(x); ()}(throw new Exception("Already has value")) } - } }