|
33 | 33 | import java.util.HashMap; |
34 | 34 | import java.util.List; |
35 | 35 | import java.util.Map; |
| 36 | +import java.util.Objects; |
36 | 37 | import java.util.ServiceLoader; |
37 | 38 | import java.util.Set; |
| 39 | +import java.util.function.Consumer; |
| 40 | +import java.util.function.Supplier; |
38 | 41 |
|
| 42 | +import jdk.internal.misc.TerminatingThreadLocal; |
39 | 43 | import jdk.internal.misc.VM; |
40 | 44 |
|
41 | 45 | import static java.nio.charset.StandardCharsets.UTF_8; |
@@ -233,6 +237,34 @@ public static <S> S loadSingle(Class<S> service, boolean required) { |
233 | 237 | return singleProvider; |
234 | 238 | } |
235 | 239 |
|
| 240 | + /** |
| 241 | + * Creates a thread-local variable that notifies {@code onThreadTermination} when a thread |
| 242 | + * terminates and it has been initialized in the terminating thread (even if it was initialized |
| 243 | + * with a null value). A typical use is to release resources associated with a thread. |
| 244 | + * |
| 245 | + * @param initialValue a supplier to be used to determine the initial value |
| 246 | + * @param onThreadTermination a consumer invoked by a thread when terminating and the |
| 247 | + * thread-local has an associated value for the terminating thread. The current |
| 248 | + * thread's value of the thread-local variable is passed as a parameter to the |
| 249 | + * consumer. |
| 250 | + */ |
| 251 | + public static <T> ThreadLocal<T> createTerminatingThreadLocal(Supplier<T> initialValue, Consumer<T> onThreadTermination) { |
| 252 | + Objects.requireNonNull(initialValue, "initialValue must be non null."); |
| 253 | + Objects.requireNonNull(onThreadTermination, "onThreadTermination must be non null."); |
| 254 | + return new TerminatingThreadLocal<>() { |
| 255 | + |
| 256 | + @Override |
| 257 | + protected T initialValue() { |
| 258 | + return initialValue.get(); |
| 259 | + } |
| 260 | + |
| 261 | + @Override |
| 262 | + protected void threadTerminated(T value) { |
| 263 | + onThreadTermination.accept(value); |
| 264 | + } |
| 265 | + }; |
| 266 | + } |
| 267 | + |
236 | 268 | /** |
237 | 269 | * A Java {@code char} has a maximal UTF8 length of 3. |
238 | 270 | */ |
|
0 commit comments