1
votes

I am sending my Scala Actor its messages from a for loop. The scala actor is receiving the messages and getting to the job of processing them. The actors are processing cpu and disk intensive tasks such as unzipping and storing files. I deduced that the Actor part is working fine by putting in a delay Thread.sleep(200) in my message passing code in the for loop.

for ( val e <- entries ) {
  MyActor ! new MyJob(e)
  Thread.sleep(100)
}

Now, my problem is that the program exits with a code 0 as soon as the for loop finishes execution. Thus preventing my Actors to finish there jobs. How do I get over this? This may be really a n00b question. Any help is highly appreciated!

Edit 1: This solved my problem for now:

while(MyActor.getState != Actor.State.Terminated)
  Thread.sleep(3000)

Is this the best I can do?

1

1 Answers

2
votes

Assume you have one actor you're want to finish its work. To avoid sleep you can create a SyncVar and wait for it to be initialized in the main thread:

val sv = new SyncVar[Boolean]

// start the actor
actor {
  // do something
  sv.set(true)
}

sv.take

The main thread will wait until some value is assigned to sv, and then be woken up.

If there are multiple actors, then you can either have multiple SyncVars, or do something like this:

class Ref(var count: Int)

val numactors = 50
val cond = new Ref(numactors)

// start your actors
for (i <- 0 until 50) actor {
  // do something

  cond.synchronized {
    cond.count -= 1
    cond.notify()
  }
}

cond.synchronized {
  while (cond.count != 0) cond.wait
}