Java : InheritableThreadLocal with Examples
InheritableThreadLocal (Java SE 21 & JDK 21) with Examples.
You will find code examples on most InheritableThreadLocal methods.
Summary
try (final var parent1 = Executors.newSingleThreadExecutor();
final var parent2 = Executors.newSingleThreadExecutor()) {
final var local = new InheritableThreadLocal<String>();
parent1.submit(() -> {
try {
System.out.println("parent 1 : set = abc");
local.set("abc");
TimeUnit.SECONDS.sleep(1);
System.out.println("parent 1 : get = " + local.get());
try (final var child = Executors.newSingleThreadExecutor()) {
child.submit(() -> {
System.out.println("child 1 : get = " + local.get());
});
}
} catch (InterruptedException e) {
System.out.println("InterruptedException!");
}
});
TimeUnit.MILLISECONDS.sleep(100);
parent2.submit(() -> {
try {
System.out.println("parent 2 : set = XYZ");
local.set("XYZ");
TimeUnit.SECONDS.sleep(1);
System.out.println("parent 2 : get = " + local.get());
try (final var child = Executors.newSingleThreadExecutor()) {
child.submit(() -> {
System.out.println("child 2 : get = " + local.get());
});
}
} catch (InterruptedException e) {
System.out.println("InterruptedException!");
}
});
}
// Result
// ↓
//parent 1 : set = abc
//parent 2 : set = XYZ
//parent 1 : get = abc
//child 1 : get = abc
//parent 2 : get = XYZ
//child 2 : get = XYZ
Constructors
InheritableThreadLocal ()
final var local = new InheritableThreadLocal<String>();
System.out.println(local.get()); // null
local.set("abc");
System.out.println(local.get()); // abc
final var local = new InheritableThreadLocal<Integer>();
System.out.println(local.get()); // null
local.set(123);
System.out.println(local.get()); // 123
Methods
protected T childValue (T parentValue)
try (final var parent = Executors.newSingleThreadExecutor()) {
final var local = new InheritableThreadLocal<String>() {
@Override
protected String childValue(String parentValue) {
System.out.println("-- childValue --");
System.out.println(" parentValue = " + parentValue);
return parentValue.toUpperCase();
}
};
parent.submit(() -> {
local.set("abc");
System.out.println("parent : get = " + local.get());
try (final var child = Executors.newSingleThreadExecutor()) {
child.submit(() -> {
System.out.println("child : get = " + local.get());
});
}
});
}
// Result
// ↓
//parent : get = abc
//-- childValue --
// parentValue = abc
//child : get = ABC
Methods declared in ThreadLocal
Related posts
- API Examples
- BlockingQueue
- Callable
- CancellationException
- ConcurrentHashMap.KeySetView
- ConcurrentLinkedDeque
- ConcurrentLinkedQueue
- ConcurrentMap
- ConcurrentModificationException
- ConcurrentSkipListSet
- Condition
- CopyOnWriteArrayList
- CopyOnWriteArraySet
- CountDownLatch
- CyclicBarrier
- Exchanger
- Executor
- ExecutorService
- Executors
- Future
- Future.State
- FutureTask
- InterruptedException
- Lock
- Runnable
- Semaphore
- Thread
- ThreadGroup
- ThreadLocal
- TimeUnit