|
| 1 | +/* |
| 2 | + * Copyright Java Operator SDK Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.javaoperatorsdk.operator.api.config; |
| 17 | + |
| 18 | +import java.lang.invoke.MethodHandle; |
| 19 | +import java.lang.invoke.MethodHandles; |
| 20 | +import java.lang.invoke.MethodType; |
| 21 | +import java.util.List; |
| 22 | +import java.util.concurrent.AbstractExecutorService; |
| 23 | +import java.util.concurrent.ExecutorService; |
| 24 | +import java.util.concurrent.Executors; |
| 25 | +import java.util.concurrent.Future; |
| 26 | +import java.util.concurrent.Semaphore; |
| 27 | +import java.util.concurrent.TimeUnit; |
| 28 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 29 | + |
| 30 | +import org.slf4j.Logger; |
| 31 | +import org.slf4j.LoggerFactory; |
| 32 | + |
| 33 | +import io.javaoperatorsdk.operator.OperatorException; |
| 34 | + |
| 35 | +/** |
| 36 | + * Creates the virtual thread based executors used when {@link |
| 37 | + * ConfigurationService#useVirtualThreads()} is enabled. |
| 38 | + * |
| 39 | + * <p>The SDK is compiled for Java 17, in which virtual threads don't exist yet, so {@code |
| 40 | + * Executors.newVirtualThreadPerTaskExecutor()} is looked up reflectively and is only available when |
| 41 | + * the operator actually runs on Java 21 or later. |
| 42 | + */ |
| 43 | +final class VirtualThreads { |
| 44 | + |
| 45 | + private static final Logger log = LoggerFactory.getLogger(VirtualThreads.class); |
| 46 | + |
| 47 | + private static final MethodHandle NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR = lookupFactoryMethod(); |
| 48 | + private static final AtomicBoolean UNSUPPORTED_WARNING_LOGGED = new AtomicBoolean(); |
| 49 | + |
| 50 | + private VirtualThreads() {} |
| 51 | + |
| 52 | + private static MethodHandle lookupFactoryMethod() { |
| 53 | + try { |
| 54 | + return MethodHandles.publicLookup() |
| 55 | + .findStatic( |
| 56 | + Executors.class, |
| 57 | + "newVirtualThreadPerTaskExecutor", |
| 58 | + MethodType.methodType(ExecutorService.class)); |
| 59 | + } catch (NoSuchMethodException | IllegalAccessException e) { |
| 60 | + log.debug("Virtual threads are not available on this JVM", e); |
| 61 | + return null; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /** Whether the JVM the operator runs on supports virtual threads, i.e. is Java 21 or later. */ |
| 66 | + static boolean isSupported() { |
| 67 | + return NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR != null; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Whether virtual threads should effectively be used, i.e. they were requested through {@link |
| 72 | + * ConfigurationService#useVirtualThreads()} <em>and</em> the JVM supports them. Requesting them |
| 73 | + * on a JVM that doesn't support them is only warned about, so that the same configuration can be |
| 74 | + * used regardless of the Java version the operator ends up running on, the only consequence being |
| 75 | + * that platform threads are used instead. Concurrency limits are enforced either way. |
| 76 | + */ |
| 77 | + static boolean shouldUse(boolean requested) { |
| 78 | + if (!requested || isSupported()) { |
| 79 | + return requested; |
| 80 | + } |
| 81 | + if (UNSUPPORTED_WARNING_LOGGED.compareAndSet(false, true)) { |
| 82 | + log.warn( |
| 83 | + "Virtual threads were requested but are not supported by the JVM in use (Java {}, Java 21" |
| 84 | + + " or later is required). Falling back to platform threads.", |
| 85 | + Runtime.version().feature()); |
| 86 | + } |
| 87 | + return false; |
| 88 | + } |
| 89 | + |
| 90 | + /** An unbounded executor starting a new virtual thread for each submitted task. */ |
| 91 | + static ExecutorService newVirtualThreadPerTaskExecutor() { |
| 92 | + if (!isSupported()) { |
| 93 | + throw new OperatorException( |
| 94 | + "Virtual threads are not supported by the JVM in use, Java 21 or later is required"); |
| 95 | + } |
| 96 | + try { |
| 97 | + return (ExecutorService) NEW_VIRTUAL_THREAD_PER_TASK_EXECUTOR.invokeExact(); |
| 98 | + } catch (Throwable e) { |
| 99 | + throw new OperatorException("Couldn't create a virtual thread per task executor", e); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * A virtual thread based executor executing at most {@code maxConcurrency} tasks at the same |
| 105 | + * time, the equivalent of a fixed size platform thread pool. |
| 106 | + */ |
| 107 | + static ExecutorService newBoundedVirtualThreadExecutor(int maxConcurrency) { |
| 108 | + return new BoundedExecutorService(newVirtualThreadPerTaskExecutor(), maxConcurrency); |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Limits how many of the tasks submitted to the wrapped executor run at the same time. |
| 113 | + * |
| 114 | + * <p>A thread is started for each task as soon as it is submitted, the task then waits for a |
| 115 | + * permit before it actually runs. This only makes sense with virtual threads, which are cheap |
| 116 | + * enough to be parked in large numbers, and has the property that submitting a task never blocks |
| 117 | + * the submitting thread, just like queuing it on a fixed size platform thread pool wouldn't. |
| 118 | + */ |
| 119 | + private static final class BoundedExecutorService extends AbstractExecutorService { |
| 120 | + |
| 121 | + private final ExecutorService delegate; |
| 122 | + private final Semaphore permits; |
| 123 | + |
| 124 | + private BoundedExecutorService(ExecutorService delegate, int maxConcurrency) { |
| 125 | + this.delegate = delegate; |
| 126 | + // fair, so that tasks run roughly in submission order as they would on a thread pool |
| 127 | + this.permits = new Semaphore(maxConcurrency, true); |
| 128 | + } |
| 129 | + |
| 130 | + @Override |
| 131 | + public void execute(Runnable command) { |
| 132 | + delegate.execute( |
| 133 | + () -> { |
| 134 | + try { |
| 135 | + permits.acquire(); |
| 136 | + } catch (InterruptedException e) { |
| 137 | + Thread.currentThread().interrupt(); |
| 138 | + // shutdownNow interrupted us before the task even started: cancel it so that whoever |
| 139 | + // waits on the associated future isn't left hanging |
| 140 | + if (command instanceof Future) { |
| 141 | + ((Future<?>) command).cancel(false); |
| 142 | + } |
| 143 | + return; |
| 144 | + } |
| 145 | + try { |
| 146 | + command.run(); |
| 147 | + } finally { |
| 148 | + permits.release(); |
| 149 | + } |
| 150 | + }); |
| 151 | + } |
| 152 | + |
| 153 | + @Override |
| 154 | + public void shutdown() { |
| 155 | + delegate.shutdown(); |
| 156 | + } |
| 157 | + |
| 158 | + @Override |
| 159 | + public List<Runnable> shutdownNow() { |
| 160 | + return delegate.shutdownNow(); |
| 161 | + } |
| 162 | + |
| 163 | + @Override |
| 164 | + public boolean isShutdown() { |
| 165 | + return delegate.isShutdown(); |
| 166 | + } |
| 167 | + |
| 168 | + @Override |
| 169 | + public boolean isTerminated() { |
| 170 | + return delegate.isTerminated(); |
| 171 | + } |
| 172 | + |
| 173 | + @Override |
| 174 | + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { |
| 175 | + return delegate.awaitTermination(timeout, unit); |
| 176 | + } |
| 177 | + } |
| 178 | +} |
0 commit comments