Java™ Platform
Standard Ed. 8
compact1, compact2, compact3
java.lang
Class ThreadLocal<T>
-
-
Constructor Summary
Constructors
| Constructor |
Description |
ThreadLocal() |
Creates a thread local variable.
|
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods
| Modifier and Type |
Method |
Description |
T |
get() |
Returns the value in the current thread's copy of this
thread-local variable.
|
protected T |
initialValue() |
Returns the current thread's "initial value" for this
thread-local variable.
|
void |
remove() |
Removes the current thread's value for this thread-local
variable.
|
void |
set(T value) |
Sets the current thread's copy of this thread-local variable
to the specified value.
|
static <S> ThreadLocal<S> |
withInitial(Supplier<? extends S> supplier) |
Creates a thread local variable.
|
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Method Detail
-
withInitial
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier)
Creates a thread local variable. The initial value of the variable is
determined by invoking the get method on the Supplier.
- Type Parameters:
S - the type of the thread local's value
- Parameters:
supplier - the supplier to be used to determine the initial value
- Returns:
- a new thread local variable
- Throws:
NullPointerException - if the specified supplier is null
- Since:
- 1.8
-
get
public T get()
Returns the value in the current thread's copy of this
thread-local variable. If the variable has no value for the
current thread, it is first initialized to the value returned
by an invocation of the
initialValue() method.
- Returns:
- the current thread's value of this thread-local
-
set
public void set(T value)
Sets the current thread's copy of this thread-local variable
to the specified value. Most subclasses will have no need to
override this method, relying solely on the
initialValue()
method to set the values of thread-locals.
- Parameters:
value - the value to be stored in the current thread's copy of
this thread-local.
-
remove
public void remove()
Removes the current thread's value for this thread-local
variable. If this thread-local variable is subsequently
read by the current thread, its value will be
reinitialized by invoking its
initialValue() method,
unless its value is
set by the current thread
in the interim. This may result in multiple invocations of the
initialValue method in the current thread.
- Since:
- 1.5
Java™ Platform
Standard Ed. 8
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2026, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.