A ThreadLocal Supplier?

Your question doesn't show the typical way to use a Supplier with a ThreadLocal. If you want a ThreadLocal of MyClass, the old (pre-1.8) way to do that was typically:

ThreadLocal<MyClass> local = new ThreadLocal<MyClass>();

// later
if (local.get() == null) {
  local.put(new MyClass());
}
MyClass myClass = local.get();

The alternative was to delcare a subclass of ThreadLocal that overrode the initialValue method.

In 1.8, you can instead use a Supplier to handle that initialization:

ThreadLocal<MyClass> local = ThreadLocal.withInitial(() -> new MyClass());

Functionally, these two are basically identical, but the Supplier version is a lot less code to write.


It depends on how the Supplier class is returned.

It needs to be synchronized in these cases:

  • Lets says it is maintaining some state between every creation, it needs to be thread safe. i.e, need to synchronize on Supplier.get() method.
  • If you are fetching the returned object from cache.

It need not be synchronized in these cases:

  • If it is simpler factory that always creates and returns the object.

In both cases, MyClass need not be synchronized. Because it is always local to thread.

Tags:

Java

Java 8