Running blocking code in map.computeIfAbsent throws error

74 Views Asked by At

I have to execute some blocking code from within a lambda function that is passed to map.computeIfAbsent() method of concurrent hashmap. however this throws error that - block()/blockFirst()/blockLast() are blocking, which is not supported in thread main.

  public Mono<String> getAccessToken(String applicationName) {

    Function<String, M2MApplicationTokenCache> mappingFunction = appName -> {
      M2MAccessToken accessToken = accessTokenWebClient.getAccessToken(applicationName).block();
      if (accessToken == null) {
        throw new AuthorizationTokenException(TOKEN_FETCH_FAILED_ERROR, appName);
      }
      return prepareCache(applicationName, accessToken); // return M2MApplicationTokenCache object
    };

    m2MApplicationTokenCaches.getCacheMap().computeIfAbsent(applicationName, mappingFunction);

    return m2MApplicationTokenCacheField
        .get(M2MApplicationTokenAggregatedKey.builder().applicationName(applicationName).build(), false)
        .map(M2MApplicationTokenAggregatedValue::getTokenValue)
        .doOnNext(out -> log.trace("Token Value : {}", out));
  }

I want to run the computeIfAbsent() method on a different thread and return a token from my cache. I have explored mono.fromCallable() but unable to put the code into that.

0

There are 0 best solutions below