Scala: Wait while List is beeing filled

Viewed 678

assume having a List where results of jobs that are computed distributed are stored.

Now I have a main thread that is waiting for all jobs finished.

I know the size of the List needs to have until all jobs are finished. What is the most elegant way in scala let the main thread (while(true) loop) sleep and getting it awake when the jobs are finished?

thanks for your answers

EDIT: ok after trying the concept from @Stefan-Kunze without success (guess I didnt got the point...) I give an example with some code:

The first node:

class PingPlugin extends SmasPlugin
{
  val messages = new ListBuffer[BaseMessage]()

  val sum = 5

  def onStop = true

  def onStart =
  {
    log.info("Ping Plugin created!")

    true
  }

  def handleInit(msg: Init)
  {
    log.info("Init received")

    for( a <- 1 to sum)
    {
      msg.pingTarget ! Ping() // Ping extends BaseMessage
    }

    // block here until all messages are received
    // wait for messages.length == sum

    log.info("handleInit - messages received: %d/%d ".format(messages.length, sum))


  }

  /**
   * This method handles incoming Pong messages
   * @param msg Pong extends BaseMessage
   */
  def handlePong(msg: Pong)
  {
    log.info("Pong received from: " + msg.sender)
    messages += msg

    log.info("handlePong - messages received: %d/%d ".format(messages.length, sum))
  }
}

a second node:

class PongPlugin extends SmasPlugin
{
  def onStop = true

  def onStart =
  {
    log.info("Pong Plugin created!")
    true
  }

  /**
   * This method receives Ping messages and send a Pong message back after a random time
   * @param msg Ping extends BaseMessage
   */
  def handlePing(msg: Ping)
  {
    log.info("Ping received from: " + msg.sender)
    val sleep: Int = math.round(5000 * Random.nextFloat())
    log.info("sleep: " + sleep)

    Thread.sleep(sleep)
    msg.sender ! Pong()
  }
}   

I guess the solution is possible with futures...

2 Answers
Related