Since I couldn't find a standard implementation of it I created this little class, but I think something simple as this should exist somewhere already:
class ReturnValue {
private var value = false
private val latch = new java.util.concurrent.CountDownLatch(1)
def setValue(aValue: Boolean) {
value = aValue
latch.countDown()
}
def getValue() = {
latch.await
value
}
}
The purpose of it is to exchange a value between two threads (main thread + EDT in my case). From the code using the getValue() method it looks almost like a Future, but the Future implementations I found expect the caller to provide the code to be executed, which doesn't work in my case.
So my questions are:
Scala standard library provides this kind of synchronization mechanism as scala.concurrent.SyncVar[T]
class.
This Scala REPL session demonstrates how it works:
scala> import concurrent._
import concurrent._
scala> import ops._
import ops._
I am importing ops._
to spawn another Thread
easily.
scala> val syncInt = new SyncVar[Int]
syncInt: scala.concurrent.SyncVar[Int] = scala.concurrent.SyncVar@17823918
scala> spawn { println("got %d" format syncInt.get) }
I am spawning another thread. get
blocks until there is a value in the syncInt
.
scala> syncInt.isSet
res1: Boolean = false
scala> syncInt.set(103)
scala> got 103
The above has been printed by the thread we created before.
scala> syncInt.isSet
res3: Boolean = true
scala> syncInt.get
res4: Int = 103
Looks somewhat similar to synchronous queue with one element, where consumer has to wait for producer to offer a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With