-
Notifications
You must be signed in to change notification settings - Fork 133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add virtual thread support #1299
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.apache.pekko.dispatch | ||
|
||
import java.util | ||
import java.util.Collections | ||
import java.util.concurrent._ | ||
import java.util.concurrent.atomic.AtomicInteger | ||
import java.util.concurrent.locks.ReentrantLock | ||
|
||
private[dispatch] class NewVirtualThreadPerTaskExecutor(threadFactory: ThreadFactory) extends AbstractExecutorService { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I will use method handle to reflection create this instead of this class |
||
import NewVirtualThreadPerTaskExecutor._ | ||
|
||
/** | ||
* 0 RUNNING | ||
* 1 SHUTDOWN | ||
* 2 TERMINATED | ||
*/ | ||
private val state = new AtomicInteger(RUNNING) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. will replace with a single field and a fieldUpdater later |
||
private val virtualThreads = ConcurrentHashMap.newKeySet[Thread]() | ||
private val terminateLock = new ReentrantLock() | ||
private val terminatedCondition = terminateLock.newCondition() | ||
|
||
override def shutdown(): Unit = { | ||
shutdown(false) | ||
} | ||
|
||
private def shutdown(interrupt: Boolean): Unit = { | ||
if (!isShutdown) { | ||
terminateLock.lock() | ||
try { | ||
if (isTerminated) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we reduce this? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please fee free to fork and change on it:( I'm a little busy at work. if we remove this, we must ensure this method is only be called when we hold the lock. |
||
() | ||
} else { | ||
if (state.compareAndSet(RUNNING, SHUTDOWN) && interrupt) { | ||
virtualThreads.forEach(thread => { | ||
if (!thread.isInterrupted) { | ||
thread.interrupt() | ||
} | ||
}) | ||
} | ||
tryTerminateAndSignal() | ||
} | ||
} finally { | ||
terminateLock.unlock() | ||
} | ||
} | ||
} | ||
|
||
private def tryTerminateAndSignal(): Unit = { | ||
if (isTerminated) { | ||
() | ||
} | ||
terminateLock.lock() | ||
try { | ||
if (isTerminated) { | ||
return | ||
} | ||
if (virtualThreads.isEmpty && state.compareAndSet(SHUTDOWN, TERMINATED)) { | ||
terminatedCondition.signalAll() | ||
} | ||
} finally { | ||
terminateLock.unlock() | ||
} | ||
} | ||
|
||
override def shutdownNow(): util.List[Runnable] = { | ||
shutdown(true) | ||
Collections.emptyList() | ||
} | ||
|
||
override def isShutdown: Boolean = state.get() >= SHUTDOWN | ||
|
||
override def isTerminated: Boolean = state.get() >= TERMINATED | ||
|
||
private def isRunning: Boolean = state.get() == RUNNING | ||
|
||
override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean = { | ||
if (isTerminated) { | ||
return true | ||
} | ||
terminateLock.lock() | ||
try { | ||
var nanosRemaining = unit.toNanos(timeout) | ||
while (!isTerminated && nanosRemaining > 0) { | ||
nanosRemaining = terminatedCondition.awaitNanos(nanosRemaining) | ||
} | ||
} finally { | ||
terminateLock.unlock() | ||
} | ||
isTerminated | ||
} | ||
|
||
// TODO AS only this execute method is been used in `Dispatcher.scala`, so `submit` and other methods is not override. | ||
override def execute(command: Runnable): Unit = { | ||
if (state.get() >= SHUTDOWN) { | ||
throw new RejectedExecutionException("Shutdown") | ||
} | ||
var started = false; | ||
try { | ||
val thread = threadFactory.newThread(Task(this, command)) | ||
virtualThreads.add(thread) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This logic here is obviously thread-unsafe because In other words, you can start and add new threads that won't be waited on while the thread-pool is shutting down. I don't know if this is a concern we need to have, or how the other implementations do it. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks, would you like to continue the work? I will continue this when find time. I have a isStarted check beblow, that would help? |
||
if (isRunning) { | ||
thread.start() | ||
started = true | ||
} else { | ||
onThreadExit(thread) | ||
} | ||
} finally { | ||
if (!started) { | ||
throw new RejectedExecutionException("Shutdown") | ||
} | ||
} | ||
} | ||
|
||
private def onThreadExit(thread: Thread): Unit = { | ||
virtualThreads.remove(thread) | ||
if (state.get() == SHUTDOWN) { | ||
tryTerminateAndSignal() | ||
} | ||
} | ||
} | ||
|
||
private[dispatch] object NewVirtualThreadPerTaskExecutor { | ||
private final val RUNNING = 0 | ||
private final val SHUTDOWN = 1 | ||
private final val TERMINATED = 2 | ||
|
||
private case class Task(executor: NewVirtualThreadPerTaskExecutor, runnable: Runnable) extends Runnable { | ||
override def run(): Unit = { | ||
try { | ||
runnable.run() | ||
} finally { | ||
executor.onThreadExit(Thread.currentThread()) | ||
} | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.apache.pekko.dispatch | ||
|
||
import org.apache.pekko.annotation.InternalApi | ||
|
||
import java.lang.invoke.{ MethodHandles, MethodType } | ||
import java.util.concurrent.ThreadFactory | ||
|
||
@InternalApi | ||
private[dispatch] object VirtualThreadSupport { | ||
|
||
/** | ||
* Returns if the current Runtime supports virtual threads. | ||
*/ | ||
def isSupported: Boolean = create("testIsSupported") ne null | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. better with a lazy val, will update later. |
||
|
||
/** | ||
* Create a virtual thread factory, returns null when failed. | ||
*/ | ||
def create(prefix: String): ThreadFactory = | ||
try { | ||
val builderClass = ClassLoader.getSystemClassLoader.loadClass("java.lang.Thread$Builder") | ||
val ofVirtualClass = ClassLoader.getSystemClassLoader.loadClass("java.lang.Thread$Builder$OfVirtual") | ||
val lookup = MethodHandles.lookup | ||
val ofVirtualMethod = lookup.findStatic(classOf[Thread], "ofVirtual", MethodType.methodType(ofVirtualClass)) | ||
var builder = ofVirtualMethod.invoke() | ||
val nameMethod = lookup.findVirtual(ofVirtualClass, "name", | ||
MethodType.methodType(ofVirtualClass, classOf[String], classOf[Long])) | ||
val factoryMethod = lookup.findVirtual(builderClass, "factory", MethodType.methodType(classOf[ThreadFactory])) | ||
builder = nameMethod.invoke(builder, prefix + "-virtual-thread-", 0L) | ||
factoryMethod.invoke(builder).asInstanceOf[ThreadFactory] | ||
} catch { | ||
case _: Throwable => null | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not look like a recursion func.