Java Locale object scope is thread or application?
I'm writing a multi-threaded Java application in which every user request creates a new thread that should use a different Locale depending on user preferences. This is not a web application so the concept of session does not apply here.
Is there any way to set the default Locale -the active one- just in the thread scope? I have been looking about it in the documentation and it does not clarify if the default Locale applies to the thread, the class loader, the process or the wh开发者_JS百科ole JVM.
Thanks. Regards.
From the Javadoc for Locale.getDefault
:
Gets the current value of the default locale for this instance of the Java Virtual Machine.
The default locale is definitely a JVM-wide variable and shouldn't be used to try keep track of the user's locale. You should take a look at Java Internationalization that discusses how to go about using these classes.
In your case it seems like you can use a ThreadLocal<Locale>
, see ThreadLocal.
On a smaller point, you mention that every user request creates a new thread.. you may want to look into using a threadpool and reusing threads as endless thread creation and destruction will hurt performance. Depending on your usage, you may also want to put a bound on this threadpool to prevent a large number of users grinding your application to a halt
精彩评论