ThreadLocal provider?

If I need a ThreadLocal variable, do I also need to use a Provider (also thread safe)?

For example, isn’t a Provider needed to ensure thread safety here?

private ThreadLocal<Supplier<MyClass>> myObject = new ThreadLocal<Supplier<MyClass>>();

Thank.

+4
source share
2 answers

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>();

// later
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.

+8
source

, .

:

  • , , . .. Supplier.get().
  • .

:

  • factory, .

MyClass . .

+3

Source: https://habr.com/ru/post/1598941/


All Articles