java - A ThreadLocal Supplier? -


if need threadlocal of variable, there need use supplier (also thread-safe)?

for example, isn't supplier unnecessary accomplish thread-safety here?

private threadlocal<supplier<myclass>> myobject = new threadlocal<supplier<myclass>>(); 

thanks.

your question doesn't show typical way use supplier threadlocal. if want threadlocal of myclass, old (pre-1.8) way typically:

threadlocal<myclass> local = new threadlocal<myclass>();  // later if (local.get() == null) {   local.put(new myclass()); } myclass myclass = local.get(); 

the alternative delcare subclass of threadlocal overrode initialvalue method.

in 1.8, can instead use supplier handle initialization:

threadlocal<myclass> local = threadlocal.withinitial(() -> new myclass()); 

functionally, these 2 identical, supplier version lot less code write.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -