4

Question: Is there a Scope for a Thread and it's spawned Threads which supports it's destruction as soon as all Threads accessing it are terminated? If not do I have to implement it myself or am I getting the concept of Scopes in Spring DI wrong?

Context:
I have a platform which has a REST-API on which processes can be started which are then running on the server. Some of these processes start multiple Threads of which some only terminate on system shutdown (e.g. listening on a stream and doing stuff with the data received).
I want to use Spring for dependency injection and now need to manage beans in a suitable scope.

Problem: I want to take parameters from the request and provide these at multiple other locations. My approach is to take a container bean which is populated in the request handler and then used at all other occasions. The @Scope("request") is destroyed as soon as the response is send which happens instantly (since the handler only spawns a Thread) thus it's not applicable here.

I read about the ThreadScope implementation from springbyexample (http://www.springbyexample.org/examples/custom-thread-scope-module.html) and a way to modify the spring SimpleThreadScope to support inheritance within the hierarchy of spawned threads (https://stackoverflow.com/a/14987371/4502203). Both are only solving parts of my Problem. What I need is a Scope which supports destruction callbacks (since I'm not keen on memory leak) and is inherited to Child-Threads.

Code Example:

@RequestMapping(value = "/myApi/{parameterA}/{parameterB}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
public  @ResponseBody void doFancyStuff(@PathVariable String parameterA, @PathVariable String parameterB) {
    new Thread(() -> {
        ParameterContainer parameterContainer = applicationContext.getBean(ParameterContainer.class);
        parameterContainer.setParA(parameterA);
        parameterContainer.setParB(parameterB);
        /*
         * spawn a couple of additional threads here which
         * need to get access to the ParameterContainer.
         */ 
    }
}
Community
  • 1
  • 1
Trinova
  • 443
  • 6
  • 18

0 Answers0