He-Pin commented on code in PR #1724:
URL: https://github.com/apache/pekko/pull/1724#discussion_r1920219797


##########
actor/src/main/scala/org/apache/pekko/dispatch/VirtualThreadSupport.scala:
##########
@@ -33,20 +34,48 @@ private[dispatch] object VirtualThreadSupport {
    */
   val isSupported: Boolean = JavaVersion.majorVersion >= 21
 
+  /**
+   * Create a virtual thread executor with the given executor as the scheduler.
+   */
+  def newThreadPerTaskExecutor(prefix: String, executor: Executor): 
ExecutorService = {
+    val factory = newVirtualThreadFactory(prefix, executor)
+    newThreadPerTaskExecutor(factory)
+  }
+
+  /**
+   * Create a virtual thread factory with the default scheduler in 
VirtualThread.
+   */
+  def newVirtualThreadFactory(prefix: String): ThreadFactory = {
+    newVirtualThreadFactory(prefix, null)
+  }
+
   /**
    * Create a virtual thread factory with a executor, the executor will be 
used as the scheduler of
    * virtual thread.
+   *
+   * The executor should run task on platform threads.
+   *
+   * returns null if not supported.
    */
-  def newVirtualThreadFactory(prefix: String): ThreadFactory = {
+  def newVirtualThreadFactory(prefix: String, executor: Executor): 
ThreadFactory = {
     require(isSupported, "Virtual thread is not supported.")
     try {
       val builderClass = 
ClassLoader.getSystemClassLoader.loadClass("java.lang.Thread$Builder")
       val ofVirtualClass = 
ClassLoader.getSystemClassLoader.loadClass("java.lang.Thread$Builder$OfVirtual")
       val ofVirtualMethod = lookup.findStatic(classOf[Thread], "ofVirtual", 
MethodType.methodType(ofVirtualClass))
       var builder = ofVirtualMethod.invoke()
+      if (executor ne null) { // Set the scheduler of virtual thread
+        val clazz = builder.getClass
+        val privateLookup = MethodHandles.privateLookupIn(
+          clazz,
+          lookup
+        )
+        val schedulerFieldSetter = privateLookup
+          .findSetter(clazz, "scheduler", classOf[Executor])
+        schedulerFieldSetter.invoke(builder, executor)

Review Comment:
   OK!, Will handle this with Java Reflection then!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscr...@pekko.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscr...@pekko.apache.org
For additional commands, e-mail: notifications-h...@pekko.apache.org

Reply via email to