Skip to content

Commit

Permalink
use methodhandle
Browse files Browse the repository at this point in the history
  • Loading branch information
pjfanning committed Jan 17, 2024
1 parent 5bd8e4f commit c0d7e15
Showing 1 changed file with 17 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package org.apache.pekko.dispatch

import com.typesafe.config.Config

import java.lang.invoke.{ MethodHandle, MethodHandles, MethodType }
import java.util.concurrent.{ ExecutorService, ForkJoinPool, ForkJoinTask, ThreadFactory }
import scala.util.Try

Expand Down Expand Up @@ -93,17 +94,26 @@ class ForkJoinExecutorConfigurator(config: Config, prerequisites: DispatcherPrer
parallelism: Int,
asyncMode: Boolean) = this(threadFactory, parallelism, asyncMode, ForkJoinPoolConstants.MaxCap)

private lazy val pekkoJdk9ForkJoinPoolClassOpt: Option[Class[_]] =
private def pekkoJdk9ForkJoinPoolClassOpt: Option[Class[_]] =
Try(Class.forName("org.apache.pekko.dispatch.PekkoJdk9ForkJoinPool")).toOption

private lazy val pekkoJdk9ForkJoinPoolHandleOpt: Option[MethodHandle] = {
pekkoJdk9ForkJoinPoolClassOpt.map { clz =>
val methodHandleLookup = MethodHandles.lookup()
val mt = MethodType.methodType(classOf[Unit], classOf[Int],
classOf[ForkJoinPool.ForkJoinWorkerThreadFactory],
classOf[Int], classOf[Thread.UncaughtExceptionHandler], classOf[Boolean])
methodHandleLookup.findConstructor(clz, mt)
}
}

def this(threadFactory: ForkJoinPool.ForkJoinWorkerThreadFactory, parallelism: Int) =
this(threadFactory, parallelism, asyncMode = true)
def createExecutorService: ExecutorService = pekkoJdk9ForkJoinPoolClassOpt match {
case Some(clz) =>
// there is only one constructor (Object conversion required by Scala 2.12)
clz.getConstructors.head.newInstance(parallelism.asInstanceOf[Object], threadFactory,
maxPoolSize.asInstanceOf[Object], MonitorableThreadFactory.doNothing,
asyncMode.asInstanceOf[Object]).asInstanceOf[ExecutorService]

def createExecutorService: ExecutorService = pekkoJdk9ForkJoinPoolHandleOpt match {
case Some(handle) =>
handle.invokeExact(parallelism, threadFactory, maxPoolSize,
MonitorableThreadFactory.doNothing, asyncMode).asInstanceOf[ExecutorService]
case _ =>
new PekkoForkJoinPool(parallelism, threadFactory, MonitorableThreadFactory.doNothing, asyncMode)
}
Expand Down

0 comments on commit c0d7e15

Please sign in to comment.