工作记录 - 使用全局变量引发的问题

使用全局变量引发的问题


有个经典的面试题:static final 修饰的全局变量List, 其地址是不变的,但是内容是可变的。

前言

最近在工作中遇到了这个问题:每次读取后,会进行加工。最终导致List越来越大。且重启后,数据会重置。

一:问题代码

@RestController
@RequestMapping(value = "demo")
public class DemoController {
    
    

    private static final List<String> STR_LIST = Lists.newArrayList("1", "2", "3", "4");

    @PostMapping(value = "m1", name = "m1")
    public void methodOne(@RequestBody JSONObject jsonObject) {
    
    
        List<String> strList = STR_LIST;
        strList.add(String.valueOf(strList.size() + 1));
        System.out.println(STR_LIST);
    }
    
}

执行结果:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

二:修正代码

@RestController
@RequestMapping(value = "demo")
public class DemoController {
    
    

    private static final List<String> STR_LIST = Lists.newArrayList("1", "2", "3", "4");

    @PostMapping(value = "m1", name = "m1")
    public void methodOne(@RequestBody JSONObject jsonObject) {
    
    
        List<String> strList = Lists.newArrayList(STR_LIST);
        strList.add(String.valueOf(strList.size() + 1));
        System.out.println(STR_LIST);
    }

}

执行结果:

[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]

总结

使用全局变量时,建议new一个对应去接收,而不是直接等于。

  List<String> strList = Lists.newArrayList(STR_LIST);

猜你喜欢

转载自blog.csdn.net/qq_37700773/article/details/126273084