|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + *--------------------------------------------------------------------------------------------*/ |
| 4 | + |
| 5 | +package com.github.copilot.sdk; |
| 6 | + |
| 7 | +import java.util.concurrent.ExecutorService; |
| 8 | +import java.util.concurrent.Executors; |
| 9 | +import java.util.logging.Logger; |
| 10 | + |
| 11 | +/** |
| 12 | + * Provides thread factories for the SDK's internal thread creation. |
| 13 | + * <p> |
| 14 | + * On Java 17, this class returns standard platform-thread factories. On Java |
| 15 | + * 21+, the multi-release JAR overlay replaces this class with one that returns |
| 16 | + * virtual-thread factories, giving the SDK lightweight threads for its |
| 17 | + * I/O-bound JSON-RPC communication without any user configuration. |
| 18 | + * <p> |
| 19 | + * The {@link java.util.concurrent.ScheduledExecutorService} used for |
| 20 | + * {@code sendAndWait} timeouts in {@link CopilotSession} is <em>not</em> |
| 21 | + * affected, because the JDK offers no virtual-thread-based scheduled executor. |
| 22 | + * |
| 23 | + * @since 0.2.2-java.1 |
| 24 | + */ |
| 25 | +final class ThreadFactoryProvider { |
| 26 | + |
| 27 | + private static final Logger LOG = Logger.getLogger(ThreadFactoryProvider.class.getName()); |
| 28 | + |
| 29 | + private ThreadFactoryProvider() { |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Creates a new daemon thread with the given name and runnable. |
| 34 | + * |
| 35 | + * @param runnable |
| 36 | + * the task to run |
| 37 | + * @param name |
| 38 | + * the thread name for debuggability |
| 39 | + * @return the new (unstarted) thread |
| 40 | + */ |
| 41 | + static Thread newThread(Runnable runnable, String name) { |
| 42 | + Thread t = new Thread(runnable, name); |
| 43 | + t.setDaemon(true); |
| 44 | + return t; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Creates a single-thread executor suitable for the JSON-RPC reader loop. |
| 49 | + * |
| 50 | + * @param name |
| 51 | + * the thread name for debuggability |
| 52 | + * @return a single-thread {@link ExecutorService} |
| 53 | + */ |
| 54 | + static ExecutorService newSingleThreadExecutor(String name) { |
| 55 | + return Executors.newSingleThreadExecutor(r -> { |
| 56 | + Thread t = new Thread(r, name); |
| 57 | + t.setDaemon(true); |
| 58 | + return t; |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Returns {@code true} when this class uses virtual threads (Java 21+ |
| 64 | + * multi-release overlay), {@code false} for platform threads. |
| 65 | + * |
| 66 | + * @return whether virtual threads are in use |
| 67 | + */ |
| 68 | + static boolean isVirtualThreads() { |
| 69 | + return false; |
| 70 | + } |
| 71 | +} |
0 commit comments