2

In java application using spring I'm facing situation when I need to create asynchronous REST endpoint for some small data processing.

I.e. current idea is:

  • we got request for processing
  • as soon as we verify it could be processed we return 200 OK
  • at the same time we create child thread in which processing will run

Child process is used because we need to have Request / Session in that processing thread (because current user should be checked and recorded during processing - due to legacy code it's hard to do before).

I use solution found on StackOverflow and it works like a charm.

However some of colleagues on review regard it "insecure" to enable inherited request context on all thread. Thus I'm looking for other possible approach.

What I tried is to share request attributes to child thread manually:

    var attrs = RequestContextHolder.getRequestAttributes();
    new Thread(() -> {
        RequestContextHolder.setRequestAttributes(attrs);
        // ...
    });

This partly works, but only till response is sent in parent thread. After this I get exception with explanation Cannot ask for request attribute - request is not active anymore!

I tried to specify that parent's attributes are inheritable - but this doesn't help:

    var attrs = RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(attrs, true);  // inheritable
    new Thread(() -> {
        RequestContextHolder.setRequestAttributes(attrs);
        // ...
    });

(I got error saying that I have no active request, If I'm not wrong - tried few more similar variations)

So any further hints are welcome (or explanations of my mistakes). Thanks in advance!

Rodion Gorkovenko
  • 2,670
  • 3
  • 24
  • 37
  • 1
    Don't, please don't try to extend a requests life over different threads, that will only lead to issues. Instead prepare the data/parameters you need and use that in a thread instead of having downstream components rely on the requests as well (basically the request should be contained to the controller and not venture out of it). – M. Deinum Jul 27 '21 at 14:50
  • Thanks for comment. Right, it is how things should be done. We all hate situations when something needs to be "wisely hacked" in order to overcome legacy issues :( – Rodion Gorkovenko Jul 27 '21 at 14:55

0 Answers0