1

I have a strange issue.
Given this code:

@RequestMapping(value = {"/randomizer"}, method = RequestMethod.POST)
    public CompletableFuture<String> randomizer(){
        CompletableFuture<String> someString = stringService
                .findRandomByInput("123")
                .thenCombine(stringService.findAnotherRandomByInput("321"), (result1, result2) -> {
                    return applyRandom(result1, result2);
                });

        CompletableFuture<Void> computation = computingService.computeRandomByInput(RandomDto.empty(), "123");

        return someString.thenCombineAsync(computation, (result1, result2) -> {
            combineIt(result1, result2, getCurrentApplicationUser());
        }, taskExecutor);
    }

By calling getCurrentApplicationUser() i´m acessing spring´s SecurityContextHolder.getContext().getAuthentication() interface.

I have this taskExecutor:

@Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(6);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("DmpkApplication-");
        executor.initialize();
        // the following is necessary because of:
        // https://stackoverflow.com/a/57434013/7320372
        return new DelegatingSecurityContextAsyncTaskExecutor(executor);
    }

So the problem is:

I call the above randomizer controller like 5 times and by the 6th time, the getAuthentication() call is null.

Sometimes the first call to the controller yields null and all other subsequent calls work.

I don´t know what´s the issue here.

Thomas Lang
  • 1,285
  • 17
  • 35

1 Answers1

1

I found a fix myself.

I renamed the above bean

public Executor taskExecutor()

the following:

public Executor executor()

Now the issue is gone. I think Spring defines already an executor itself. The previous taskExecutor was an additional one. But somehow the Spring one executor got called which is not a DelegatingSecurityContextAsyncTaskExecutor by default.

So maybe that is the issue.

Nevermind - now it works!

Thomas Lang
  • 1,285
  • 17
  • 35