How to designate a thread pool for actors
Asked Answered
R

3

12

I have an existing java/scala application using a global thread pool. I would like to start using actors in the project but would like everything in the app using the same pool.

I know I can set the maximum number of threads that actors use but would prefer sharing the thread pool. Is this necessary/reasonable, and is it possible to designate the actor's thread pool?

If it is not possible/recommended, are there any rules of thumb when integrating actors in apps that are already using threads?

Thanks.

Rembrandt answered 20/10, 2009 at 23:31 Comment(0)
T
7

I believe you can do something like this:

trait MyActor extends Actor {
  val pool = ... // git yer thread pool here
  override def scheduler = new SchedulerAdapter {
    def execute(block: => Unit) =
      pool.execute(new Runnable {
        def run() { block }
      })
  }
} 
Taishataisho answered 20/10, 2009 at 23:41 Comment(1)
I guess you should write "val scheduler =" instead of "def scheduler =", otherwise you'll have multiple instances of schedulers.Job
D
6

For Scala 2.8.1 it's:

scala -Dactors.corePoolSize=20
Dropping answered 19/1, 2011 at 17:41 Comment(0)
R
2

But it's quite easy to re-use the thread pool used by the actor subsystem. Firstly you can control it's size:

-Dactors.maxPoolSize=8

And you can invoke work on it:

actors.Scheduler.execute( f ); //f is => Unit

The only thing it lacks is the ability to schedule work. For this I use a separate ScheduledExecutorService which is single-threaded and runs its work on the actors thread pool:

object MyScheduler {
  private val scheduler = Executors.newSingleThreadedScheduledExecutorService

  def schedule(f: => Unit, delay: (Long, TimeUnit)) : ScheduledFuture[_] = {
      scheduler.schedule(new ScheduledRun(f), delay._1, delay._2)
  }

  private class ScheduledRun(f: => Unit) extends Runnable {
    def run = actors.Scheduler.execute(f)
  }

}

Then you can use this to schedule anything:

MyScheduler.schedule(f, (60, SECONDS))
Ragland answered 21/10, 2009 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.