Skip to content

java.lang.ThreadLocal Class in Java

Ramesh Fadatare edited this page Aug 29, 2018 · 4 revisions

Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share its variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.

ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

ThreadLocal Class Constructors

ThreadLocal() - Creates a thread local variable.

ThreadLocal Class Methods

  • 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 ThreadLocal withInitial(Supplier<? extends S> supplier) - Creates a thread local variable.

ThreadLocal Class Example

In this example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalExample {
	// Atomic integer containing the next thread ID to be assigned
	private static final AtomicInteger nextId = new AtomicInteger(0);

	// Thread local variable containing each thread's ID
	private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
		@Override
		protected Integer initialValue() {
			return nextId.getAndIncrement();
		}
	};

	// Returns the current thread's unique ID, assigning it if necessary
	public static int get() {
		return threadId.get();
	}
}

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).