Course contentsShow
← Java
Lesson 2635 of 2,87048. Concurrency FundamentalsFree lesson

ThreadLocal.initialValue() for Default Values

Overriding initialValue() to provide default values when a thread first accesses the ThreadLocal.

ThreadLocal.initialValue() for Default Values

What you'll learn: How to override initialValue() to automatically provide a default value whenever a new thread first accesses your ThreadLocal variable.


The Problem with Manual Initialization

In the previous lesson, you learned to use ThreadLocal.get() and set(). But what happens when a thread calls get() before anyone has called set() for that thread? By default, ThreadLocal.get() returns null. This forces you to check for null every time, which is tedious and error-prone.

Overriding initialValue()

The ThreadLocal class provides a protected method called initialValue() that you can override to supply a default value. This method is called automatically the first time a thread accesses the ThreadLocal with get(), but only if no value has been set() yet for that thread.

ThreadLocal<Integer> counter = new ThreadLocal<>() {
    @Override
    protected Integer initialValue() {
        return 0;  // Every thread starts with 0
    }
};

Now when any thread calls counter.get() for the first time, it automatically receives 0 instead of null.

How It Works

Think of initialValue() as a factory method that runs once per thread, on-demand. Each thread's first get() triggers the creation of its own independent default value. Subsequent get() calls return the stored value without calling initialValue() again.

// Thread A's first access
int value = counter.get();  // initialValue() runs, returns 0
counter.set(value + 1);     // Now Thread A has 1

// Thread B's first access
int bValue = counter.get(); // initialValue() runs again, returns 0 for B

Key Takeaway: Override ThreadLocal.initialValue() to provide automatic, per-thread default values, eliminating null checks and ensuring each thread starts with a clean, predictable state.