Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call this kind of concurrency related class? And is there a standard implementation?

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:

  • Is there a name for such a thingy?
  • Is there a standard implementation for it in java or scala?
  • Is my implementation even correct?
like image 492
Jens Schauder Avatar asked Feb 14 '11 07:02

Jens Schauder


2 Answers

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
like image 60
Alexander Azarov Avatar answered Oct 15 '22 05:10

Alexander Azarov


Looks somewhat similar to synchronous queue with one element, where consumer has to wait for producer to offer a value.

like image 5
Vasil Remeniuk Avatar answered Oct 15 '22 07:10

Vasil Remeniuk