Java - Set the initial value for thread-local variable

Introduction

initialValue() method sets the initial value of the thread-local variable for each thread.

You can set the initial value for the call counter to 1000 by using an anonymous class as shown:

ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
    @Override
    public Integer initialValue() {
            return 1000;
    }
};

You can use a factory method called withInitial() in the ThreadLocal class that can specify an initial value.

// Create a ThreadLocal with an initial value of 1000
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1000);

Return the second of the current time as the initial value

ThreadLocal<Integer> threadLocal = 
         ThreadLocal.withInitial(() -> LocalTime.now().getSecond());

Related Topic