user67339
user67339

Reputation: 71

Is it a bad practice to save thread local values in static final field?

I came across following code in a legacy system,

private static final ThreadLocal<DateFormat> dateFormatThreadLocal = new ThreadLocal(){

    @Override
    protected Object initialValue() {
        //Set initial value
        return new SimpleDateFormat("");
    }
};


private static final DateFormat someValue = dateFormatThreadLocal.get();

However, I have following questions.

1.) Is it a good idea to define thread locals as final. ( I know static is fine)

2.) Is it a good idea to hold thread local.get() call in a static (or both static and final) instance variable? ( if we do this doesn't it hinder the whole purpose of having thread-local at first place )

Upvotes: 2

Views: 628

Answers (1)

1.) Is it a good idea to define thread locals as final. ( I know static is fine)

If you are not assigning to dateFormatThreadLocal then final makes no difference. However, it's generally a good idea, because it prevents you from accidentally assigning to it.

2.) Is it a good idea to hold thread local.get() call in a static (or both static and final) instance variable? ( if we do this doesn't it hinder the whole purpose of having thread-local at first place )

No it is not. Actually, if you do do this then it defeats the whole purpose of having thread-local in the first place.

Whichever thread happens to load the class first will retrieve its SimpleDateFormat, and store a reference to that object in someValue. And then whenever you use someValue, the current thread will use that thread's SimpleDateFormat (that it got before) instead of calling dateFormatThreadLocal.get() and getting its own one.

If you're using ThreadLocal then presumably you don't want every thread to use the same object - otherwise why bother using it?

Upvotes: 5

Related Questions