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

ThreadLocal.withInitial() Factory Method

Using the withInitial() static factory method with a Supplier for cleaner initialization code.

ThreadLocal.withInitial() Factory Method

You'll learn: How to use ThreadLocal.withInitial() with a Supplier to create thread-local variables with cleaner, more concise initialization code.

The Cleaner Alternative to initialValue()

In the previous lesson, you learned about overriding initialValue() to provide default values for ThreadLocal variables. Java 8 introduced a more elegant approach: the withInitial() static factory method.

Instead of creating an anonymous subclass and overriding initialValue(), you can pass a Supplier lambda directly to withInitial(). This factory method creates the ThreadLocal instance and handles the initialization logic in one clean expression.

The Syntax

ThreadLocal<Integer> threadId = ThreadLocal.withInitial(() -> 1);
ThreadLocal<List<String>> threadBuffer = ThreadLocal.withInitial(() -> new ArrayList<>());

The lambda expression you provide is a Supplier<T> that will be invoked the first time a thread calls get() on that ThreadLocal, just like initialValue() worked.

Why It's Better

Compare the old way:

ThreadLocal<Integer> oldWay = new ThreadLocal<Integer>() {
    @Override
    protected Integer initialValue() {
        return 1;
    }
};

With the new way:

ThreadLocal<Integer> newWay = ThreadLocal.withInitial(() -> 1);

The withInitial() approach eliminates boilerplate, improves readability, and aligns with modern Java's functional programming style. Each thread still gets its own independent initial value when it first accesses the variable.

Key Takeaway:
Use ThreadLocal.withInitial() with a Supplier lambda for concise, readable thread-local initialization without anonymous subclasses or overriding methods.