Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Spring Controllers Thread-Safe

Tags:

java

spring

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();
    }
}
like image 378
EdgeCase Avatar asked Jan 03 '13 19:01

EdgeCase


People also ask

Are spring singletons thread-safe?

Spring singleton beans are NOT thread-safe just because Spring instantiates them.

Is spring boot thread-safe?

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.

Are Autowired bean thread-safe?

Answer: No. Spring don't give you thread safety for their bean.

Is JPA thread-safe?

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.


1 Answers

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.

like image 172
digitaljoel Avatar answered Oct 11 '22 16:10

digitaljoel