Scala类实例变量由两个映射组成?

时间:2018-03-28 21:48:34

标签: scala

我试图理解一些Scala代码中的数据结构我正在阅读(许可证是Apache,这只是一个很小的摘录)。我感兴趣的是 pool 的性质。数据结构是2个独立的地图/数组/列表是什么意思?

class TaskQueueAsync( numThreads: Int, queuesSize: Int ) extends TaskQueue
{
  private val lock  = new ReentrantReadWriteLock( true )
  private val pools = ( 1 to numThreads )
                      .map( _ => new ArrayBlockingQueue[Runnable]( queuesSize, true ) )
                      .map( q => new ThreadPoolExecutor( 1, 1, 1, DAYS, q,
                                  new BasicThreadFactory.Builder()
                                      .namingPattern( "indexer-%d" )
                                      .build(),
                                  ( task, executor ) =>
                                      if( !executor.isShutdown )
                                        executor.getQueue.put( task ) ) )

我可以帮助了解这里发生了什么吗?如何设置?它是什么样子的? (也许,"它在Java中看起来像什么?")

1 个答案:

答案 0 :(得分:5)

我会尝试对pools逻辑进行注释,希望这会有所帮助:

private val pools =
  // start with a range from 1 to numThreads, which you can essentially
  // consider a Seq(1, 2, 3, ..., numThreads)
  ( 1 to numThreads )
      // now, for each value in that range, pass it to this function and store
      // the results in another sequence. The function ignores the input value
      // (which is what the _ means before the arrow) and returns a
      // new ArrayBlockingQueue[Runnable]. After this step, we will have
      // a Seq[ArrayBlockingQueue[Runnable]], with a number of elements
      // equal to numThreads
      .map( _ => new ArrayBlockingQueue[Runnable]( queuesSize, true ) )
      // Again, for each of these ArrayBlockingQueues, pass it to this
      // new function (captured in the q argument) and create a new Seq
      // of the results. In this case, it is a Seq[ThreadPoolExecutor]
      // where each of the ThreadPoolExecutor objects has been through the
      // initialization code below
      .map( q => new ThreadPoolExecutor( 1, 1, 1, DAYS, q,
                              new BasicThreadFactory.Builder()
                                  .namingPattern( "indexer-%d" )
                                  .build(),
                              ( task, executor ) =>
                                  if( !executor.isShutdown )
                                    executor.getQueue.put( task ) ) )

因此pools的最终结果类型应为Seq[ThreadPoolExecutor],并且它将具有等于numThreads的多个元素。希望这有助于澄清发生了什么。