When should I use a ThreadLocal variable?
How is it used?
Nothing really new here, but I discovered today that ThreadLocal
is very useful when using Bean Validation in a web application. Validation messages are localized, but by default use Locale.getDefault()
. You can configure the Validator
with a different MessageInterpolator
, but there's no way to specify the Locale
when you call validate
. So you could create a static ThreadLocal
(or better yet, a general container with other things you might need to be ThreadLocal
and then have your custom MessageInterpolator
pick the Locale
from that. Next step is to write a ServletFilter
which uses a session value or request.getLocale()
to pick the locale and store it in your ThreadLocal
reference.