3

I'm translating an application based on REST using Spring Framework. Now I need to translate some responses based on the language of the request. For example:

/get-me-an-answer/?lang=es Spanish
/get-me-an-answer/?lang=en English
/get-me-an-answer/?lang=fr French

I have the variable language_code as a static variable in a class named Translang

    class Translang {
...
        public static String language_code = null;
...
    }

The problem is with multithreading, when a new request come will change the language and if another previous request is executing can probably answer in the language modified and not in the original language it requested.

That's the reason of my question: How can I have a global variable in Spring per request to avoid this problem?

  • Why do you need a static variable, you can process the url param right? – Stefan Nov 23 '17 at 14:40
  • yes I can, but I probably pass through multiple methods, I want to avoid that workload, simply the method that wants to use it access the static variable or how can I do it? – Desafio Guerreros Limited Nov 23 '17 at 14:52
  • You should keep passing it through, because Rest is stateless and when you're setting a state (like language) strange results will occur. You should just pass the value to underlying methods. – Stefan Nov 23 '17 at 14:58
  • See also https://stackoverflow.com/questions/33049674/elegant-way-to-get-locale-in-spring-controller for a better way to get the language of the user. This supports the standard `Accept-Language` header. – Wim Deblauwe Nov 23 '17 at 15:28

2 Answers2

1

Seems that ThreadLocal is what you are looking for as per request is performed by a separate thread.

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

Mikita Harbacheuski
  • 2,193
  • 8
  • 16
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/18046225) – Omi Nov 23 '17 at 22:41
  • Sounds reasonable, more details were added in original answer. – Mikita Harbacheuski Nov 23 '17 at 22:50
0

I would suggest to implement a context that navigates throw the flow of your request, so with this, you will pass this context among the entire transaction, once you have that domain element, you need to create a new one by each request that you receive. Currently your class is not thread safe, this can be fixed also changing the scope of your bean.

montusokar
  • 198
  • 8