thread-local

When and how should I use a ThreadLocal variable?

一曲冷凌霜 提交于 2019-11-26 00:17:16
问题 When should I use a ThreadLocal variable? How is it used? 回答1: One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object. For example: public class Foo { // SimpleDateFormat is not thread-safe, so give one to each thread private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat