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();
}
}
Spring singleton beans are NOT thread-safe just because Spring instantiates them.
How We Achieve Thread Safety In Spring Boot? The default front controller (web server) for spring boot web application is Servlet which it creates a new separate thread for every http request. Servlet then delegates the control flow to the lower layers beginning from controller layer.
Answer: No. Spring don't give you thread safety for their bean.
You don't need to make those methods synchronized, they are thread safe as it is. Yeah, it probably makes sense to make DbService a singleton. Alternatively, you could just make em static.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With