Reputation: 4827
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.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class TestController {
private final Gson gson = new Gson();
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(HttpServletResponse res, HttpServletRequest req) throws IOException {
HashMap<String, String> hm = new HashMap();
res.getWriter().print(gson.toJson(results));
res.getWriter().close();
}
}
Upvotes: 13
Views: 12319
Reputation: 26584
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.
Upvotes: 13
Reputation: 10997
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.
Upvotes: 0
Reputation: 2005
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.
Upvotes: 1
Reputation: 1663
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.
Upvotes: 1