简体   繁体   中英

ThreadLocal initialValue() vs set()

I understand the purpose of ThreadLocal class; but bit baffled by the methods initialValue() and set() . To me, both seems to be having the same purpose - to set the value to the ThreadLocal object so that each thread will get its own copy.

Regardless of whether initialValue() or set() is used to set the value, you always get the value by calling the get() method.

You can remove the value by calling the remove() method.

  1. When do we need to use the initialValue() method?
  2. When do we need to use the set() method?

First of all, initValue() is a protected method, which means you can not use it outside the ThreadLocal class or it's children. It serves one purpose only, which it's name suggests, to provide initial value and is invoked only once.

If you look at the class, you'll find that internally, initValue() always returns null unless you provide a Supplier with ThreadLocal.withInitial(Supplier supplier) or override this method in your own extension of ThreadLocal .

Do read the docs for details. They always help-

https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html

Hope this helps. Happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM