Java : ThreadLocal - API使用例
ThreadLocal (Java SE 21 & JDK 21) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様書のおともにどうぞ。
概要
ThreadLocal クラスは、変数を各スレッドに紐づけて管理します。
そのため、ThreadLocal 自体のインスタンスは複数のスレッドで共有でき、かつ、スレッドごとに独立した変数を get/set できます。
class SharedTask implements Runnable {
private final ThreadLocal<Integer> local = ThreadLocal.withInitial(() -> 0);
@Override
public void run() {
try {
final var count = local.get() + 1;
final var id = Thread.currentThread().threadId();
System.out.printf("thread id = %d : count = %d%n", id, count);
TimeUnit.MILLISECONDS.sleep(100);
local.set(count);
} catch (InterruptedException e) {
System.out.println("InterruptedException!");
}
}
}
try (final var executor = Executors.newFixedThreadPool(3)) {
final var sharedTask = new SharedTask();
for (int i = 0; i < 9; i++) {
executor.submit(sharedTask);
}
}
// 結果
// ↓
//thread id = 32 : count = 1
//thread id = 33 : count = 1
//thread id = 34 : count = 1
//thread id = 32 : count = 2
//thread id = 33 : count = 2
//thread id = 34 : count = 2
//thread id = 32 : count = 3
//thread id = 33 : count = 3
//thread id = 34 : count = 3
コンストラクタ
ThreadLocal ()
final var local = new ThreadLocal<String>();
System.out.println(local.get()); // null
local.set("abc");
System.out.println(local.get()); // abc
final var local = new ThreadLocal<Integer>();
System.out.println(local.get()); // null
local.set(123);
System.out.println(local.get()); // 123
メソッド
T get ()
class SharedTask implements Runnable {
private final ThreadLocal<Integer> local = ThreadLocal.withInitial(() -> 0);
@Override
public void run() {
try {
final var count = local.get() + 1;
final var id = Thread.currentThread().threadId();
System.out.printf("thread id = %d : count = %d%n", id, count);
TimeUnit.MILLISECONDS.sleep(100);
local.set(count);
} catch (InterruptedException e) {
System.out.println("InterruptedException!");
}
}
}
try (final var executor = Executors.newFixedThreadPool(3)) {
final var sharedTask = new SharedTask();
for (int i = 0; i < 9; i++) {
executor.submit(sharedTask);
}
}
// 結果
// ↓
//thread id = 32 : count = 1
//thread id = 33 : count = 1
//thread id = 34 : count = 1
//thread id = 32 : count = 2
//thread id = 33 : count = 2
//thread id = 34 : count = 2
//thread id = 32 : count = 3
//thread id = 33 : count = 3
//thread id = 34 : count = 3
protected T initialValue ()
関連 : withInitial(Supplier<? extends S> supplier)
final var local = new ThreadLocal<String>() {
@Override
protected String initialValue() {
return "abc";
}
};
System.out.println(local.get()); // abc
local.set("XYZ");
System.out.println(local.get()); // XYZ
void remove ()
final var local = ThreadLocal.withInitial(() -> "abc");
System.out.println(local.get()); // abc
local.set("XYZ");
System.out.println(local.get()); // XYZ
local.remove();
System.out.println(local.get()); // abc
final var local = new ThreadLocal<Integer>();
System.out.println(local.get()); // null
local.set(123);
System.out.println(local.get()); // 123
local.remove();
System.out.println(local.get()); // null
void set (T value)
このメソッドの使用例は、get() にまとめて記載しました。
そちらのAPI使用例をご参照ください。
static <S> ThreadLocal<S> withInitial (Supplier<? extends S> supplier)
final var local = ThreadLocal.withInitial(() -> "abc");
System.out.println(local.get()); // abc
local.set("XYZ");
System.out.println(local.get()); // XYZ
関連記事
- API 使用例
- 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 (同期)
- Object (オブジェクト)
- Runnable
- Semaphore (セマフォ)
- Thread (スレッド)
- ThreadGroup
- ThreadLocal
- TimeUnit