Alessandro
Alessandro

Reputation: 4472

Store temporary data in a Spring Controller

I'm wondering if I could store temporary data in a class attribute of a Controller. My doubt is about the concurrency calls. Let us, for example, consider the following code:

@Controller
public class TestController {
    @Autowired
    private TestService testService;

    @Autowired
    private OtherService otherService;

    private final HashMap<Integer, Test> testMap = new HashMap<Integer, Test>();

    @RequestMapping(value = "test")
    @ResponseBody
    public List<Test> test() {
        List<Test> list = new ArrayList<Test>();
        for (final OtherTest otherTest : otherService.getAll()) {
            Integer key = otherTest.getId();
            final Test t;
            if(testMap.containsKey(key)) {
                t = testMap.get(key);
            } else {
                t = testService.getByOtherTestId(key);
            }
            list.add(t);
        }
    }
}

I know that Controllers are Beans, and I know that Beans are Singleton, so:

What happen if two users call the test method at the same time? Each one of them read/write the same testMap object? When the testMap object lose its scope and will be re-instantiated?

Thanks

Upvotes: 1

Views: 4460

Answers (1)

Mahozad
Mahozad

Reputation: 24582

Yes, the two requests would manipulate the same testMap object. If you want to create a new Map for every request you can create a bean for it in one of your configuration classes:

@Bean
@RequestScope // or @Scope("request")
public Map<Integer, Test> testMap() {
    return new HashMap<>();
}

and autowire it in your controller:

@Autowired
private Map<Integer, Test> testMap;

Upvotes: 1

Related Questions