天天看點

Spring MVC 中的 Controller 是多例還是單列

前言

單例模式(Singleton)是程式設計中一種非常重要的設計模式,設計模式也是Java面試重點考察的一個方面。面試經常會問到的一個問題是:SpringMVC中的Controller是單例還是多例,很多同學可能會想當然認為Controller是多例,其實不然。
Spring MVC 中的 Controller 是多例還是單列

根據Tomcat官網中的介紹,對于一個浏覽器請求,tomcat會指定一個處理線程,或是線上程池中選取空閑的,或者建立一個線程。

Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCountattribute). Any further simultaneous requests will receive “connection refused” errors, until resources are available to process them.

—— https://tomcat.apache.org/tomcat-7.0-doc/config/http.html

在Tomcat容器中,每個servlet是單例的。在SpringMVC中,Controller 預設也是單例。 采用單例模式的最大好處,就是可以在高并發場景下極大地節省記憶體資源,提高服務抗壓能力。

單例模式容易出現的問題是:在Controller中定義的執行個體變量,在多個請求并發時會出現競争通路,Controller中的執行個體變量不是線程安全的。

Controller不是線程安全的

正因為Controller預設是單例,是以不是線程安全的。如果用SpringMVC 的 Controller時,盡量不在 Controller中使用執行個體變量,否則會出現線程不安全性的情況,導緻資料邏輯混亂。

舉一個簡單的例子,在一個Controller中定義一個非靜态成員變量 num 。通過Controller成員方法來對 num 增加。

@Controller
public class TestController {
    private int num = 0;

    @RequestMapping("/addNum")
    public void addNum() {
        System.out.println(++num);
    }
}      

在本地運作後:

首先通路 http:// localhost:8080 / addNum,得到的答案是1;

再次通路 http:// localhost:8080 / addNum,得到的答案是 2。

兩次通路得到的結果不同,num已經被修改,并不是我們希望的結果,接口的幂等性被破壞。

從這個例子可以看出,所有的請求通路同一個Controller執行個體,Controller的私有成員變量就是線程共用的。某個請求對應的線程如果修改了這個變量,那麼在别的請求中也可以讀到這個變量修改後的的值。

Controller并發安全的解決辦法

如果要保證Controller的線程安全,有以下解決辦法:

盡量不要在 Controller 中定義成員變量 ;

如果必須要定義一個非靜态成員變量,那麼可以通過注解 @Scope(“prototype”) ,将Controller設定為多例模式。

@Controller
@Scope(value="prototype")
public class TestController {
    private int num = 0;

    @RequestMapping("/addNum")
    public void addNum() {
        System.out.println(++num);
    }
    }      

Scope屬性是用來聲明IOC容器中的對象(Bean )允許存在的限定場景,或者說是對象的存活空間。在對象進入相應的使用場景之前,IOC容器會生成并裝配這些對象;當該對象不再處于這些使用場景的限定時,容器通常會銷毀這些對象。

Controller也是一個Bean,預設的 Scope 屬性為Singleton ,也就是單例模式。如果Bean的 Scope 屬性設定為 prototype 的話,容器在接受到該類型對象的請求時,每次都會重新生成一個新的對象給請求方。

Controller 中使用 ThreadLocal 變量。 每一個線程都有一個變量的副本。

public class TestController {
    private int num = 0;
    private final ThreadLocal <Integer> uniqueNum =
             new ThreadLocal <Integer> () {
                 @Override protected Integer initialValue() {
                     return num;
                 }
             };

    @RequestMapping("/addNum")
    public void addNum() {
        int unum = uniqueNum.get();
       uniqueNum.set(++unum);
       System.out.println(uniqueNum.get());
    }
}