|
27 | 27 | import java.util.concurrent.Executor;
|
28 | 28 | import java.util.concurrent.ExecutorService;
|
29 | 29 | import java.util.concurrent.ScheduledExecutorService;
|
| 30 | +import java.util.concurrent.TimeUnit; |
30 | 31 | import java.util.function.BiConsumer;
|
31 | 32 | import java.util.function.BiFunction;
|
32 | 33 | import java.util.function.Consumer;
|
@@ -135,9 +136,37 @@ static Executor taskWrapping(Executor executor) {
|
135 | 136 | * @since 1.1.0
|
136 | 137 | */
|
137 | 138 | static ExecutorService taskWrapping(ExecutorService executorService) {
|
| 139 | + if (executorService instanceof CurrentContextExecutorService) { |
| 140 | + return executorService; |
| 141 | + } |
138 | 142 | return new CurrentContextExecutorService(executorService);
|
139 | 143 | }
|
140 | 144 |
|
| 145 | + /** |
| 146 | + * Returns an {@link ScheduledExecutorService} which delegates to the provided {@code |
| 147 | + * executorService}, wrapping all invocations of {@link ExecutorService} methods such as {@link |
| 148 | + * ExecutorService#execute(Runnable)} or {@link ExecutorService#submit(Runnable)} with the |
| 149 | + * {@linkplain Context#current() current context} at the time of invocation. |
| 150 | + * |
| 151 | + * <p>This is generally used to create an {@link ScheduledExecutorService} which will forward the |
| 152 | + * {@link Context} during an invocation to another thread. For example, you may use something like |
| 153 | + * {@code ScheduledExecutorService dbExecutor = Context.wrapTasks(threadPool)} to ensure calls |
| 154 | + * like {@code dbExecutor.execute(() -> database.query())} have {@link Context} available on the |
| 155 | + * thread executing database queries. |
| 156 | + * |
| 157 | + * <p>Note: The context will not be propagated for {@link |
| 158 | + * ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} and {@link |
| 159 | + * ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)} calls. |
| 160 | + * |
| 161 | + * @since 1.43.0 |
| 162 | + */ |
| 163 | + static ScheduledExecutorService taskWrapping(ScheduledExecutorService executorService) { |
| 164 | + if (executorService instanceof CurrentContextScheduledExecutorService) { |
| 165 | + return executorService; |
| 166 | + } |
| 167 | + return new CurrentContextScheduledExecutorService(executorService); |
| 168 | + } |
| 169 | + |
141 | 170 | /**
|
142 | 171 | * Returns the value stored in this {@link Context} for the given {@link ContextKey}, or {@code
|
143 | 172 | * null} if there is no value for the key in this context.
|
|
0 commit comments