Are Spring Controllers Thread-Safe

前端 未结 4 1333
你的背包
你的背包 2021-02-05 18:21

I came upon this Controller example, and am wondering if it is thread-safe? I am wondering specifically about the gson instance variable.

import org.springframe         


        
相关标签:
4条回答
  • 2021-02-05 18:29

    Gson is definitely thread safe and was made this way back in 2008, so as long as your version is post that then it should be fine. I see no thread safety issues with your code. Although I would make the instance of Gson static.

    0 讨论(0)
  • 2021-02-05 18:35

    Just like servlets controller request handler methods are also not thread safe. Ie a multiple request to /test may make many threads execute test method.

    In your example you dont have to worry about thread safety as gson.toJson(results) is the only operation on gson and seems like it wont alter the state of that object.

    0 讨论(0)
  • 2021-02-05 18:42

    To answer the question in the title, "Are Spring Controllers Thread-Safe", Spring Controllers are singletons, therefore they SHOULD be implemented in a thread safe manner but it's up to you to ensure that your implementation is ACTUALLY thread safe.

    In the code you post you should be fine since as others have pointed out, GSON is thread safe.

    0 讨论(0)
  • 2021-02-05 18:45

    Assuming that this controller is created as a normal Spring "singleton" bean, the answer is no.

    You could create the controller as a prototype bean, in which case a new instance would be created for each request. A better idea, if you want to do this, is to define your bean's scope as request.

    However, I question the reason for any controller object to have member variables, aside from the possibility of incorrectly scoping the bean. It's an indication that the controller is trying to do too much work, and that some of that work should be offloaded to a service or helper class. The only things that an MVC controller should do arepass request data on to a service layer, and retrieve data to be displayed by a view.

    0 讨论(0)
提交回复
热议问题