Your question does not show a typical way to use the Provider with ThreadLocal. If you want ThreadLocal MyClass, the old (before 1.8) way to do this is usually:
ThreadLocal<MyClass> local = new ThreadLocal<MyClass>();
if (local.get() == null) {
local.put(new MyClass());
}
MyClass myClass = local.get();
An alternative was to consider a subclass ThreadLocalthat redefined the method initialValue.
In 1.8, you can instead use the Provider to handle this initialization:
ThreadLocal<MyClass> local = ThreadLocal.withInitial(() -> new MyClass());
Functionally, the two are basically identical, but the provider version is much smaller than the code for writing.
Sbodd source
share