Work record - problems caused by using global variables

Problems caused by using global variables


There is a classic interview question: the address of the global variable List modified by static final is unchanged, but the content is variable.

Preface

I encountered this problem at work recently: after each reading, processing will be performed. Eventually the List becomes larger and larger. And after restarting, the data will be reset.

1: Problem code

@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);
    }
    
}

Results of the:

[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]

Two: Correct the code

@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);
    }

}

Results of the:

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

Summarize

When using global variables, it is recommended to use new to receive them instead of directly equaling them.

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

Guess you like

Origin blog.csdn.net/qq_37700773/article/details/126273084