Spring控制器是否是线程安全的 [英] Are Spring Controllers Thread-Safe

查看:236
本文介绍了Spring控制器是否是线程安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个Controller示例,我想知道它是否是线程安全的?我特别想知道gson实例变量。

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控制器是单例,因此它们应该以线程安全的方式实现,但是由您来确保您的实现实际上是线程安全的。

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.

在您发布的代码中,您应该没问题,因为正如其他人所指出的那样,GSON是线程安全的。

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

这篇关于Spring控制器是否是线程安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆