【问题标题】:How to designate a thread pool for actors如何为actor指定线程池
【发布时间】:2011-01-20 01:41:38
【问题描述】:

我有一个使用全局线程池的现有 java/scala 应用程序。我想开始在项目中使用演员,但希望应用程序中的所有内容都使用同一个池。

我知道我可以设置参与者使用的最大线程数,但我更愿意共享线程池。这是否必要/合理,是否可以指定actor的线程池?

如果不可能/不推荐,在已经使用线程的应用程序中集成参与者时是否有任何经验法则?

谢谢。

【问题讨论】:

    标签: scala multithreading actor pool


    【解决方案1】:

    我相信你可以这样做:

    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 }
          })
      }
    } 
    

    【讨论】:

    【解决方案2】:

    对于 Scala 2.8.1,它是:

    scala -Dactors.corePoolSize=20
    

    【讨论】:

      【解决方案3】:

      但是重用actor子系统使用的线程池是相当容易的。首先你可以控制它的大小:

      -Dactors.maxPoolSize=8
      

      你可以调用它的工作:

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

      它唯一缺乏的是安排工作的能力。为此,我使用了一个单独的ScheduledExecutorService,它是单线程,并在参与者线程池上运行它的工作:

      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)
        }
      
      }
      

      然后你可以用它来安排任何事情:

      MyScheduler.schedule(f, (60, SECONDS))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-04
        • 2012-05-27
        相关资源
        最近更新 更多