Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async support for CacheLoader / AdvancedCacheLoader #93

Closed
cruftex opened this issue Sep 17, 2018 · 2 comments
Closed

Async support for CacheLoader / AdvancedCacheLoader #93

cruftex opened this issue Sep 17, 2018 · 2 comments
Assignees
Labels
Milestone

Comments

@cruftex
Copy link
Member

cruftex commented Sep 17, 2018

General useful for reactive programming.

Useful together with refresh ahead. See: ben-manes/caffeine#261

@cruftex
Copy link
Member Author

cruftex commented Aug 13, 2020

Shipped as preview in 1.3.2.Alpha and looks good. Tested it in a small internal project and looks good.

Here is an example for using the async Java 11 http client with cache2k:

public class GitHubStatisticsJava11Source implements AsyncCacheLoader<String, GitHubCounters> {

  private HttpClient client = HttpClient.newHttpClient();

  public void load(String key, Context<String, GitHubCounters> context, final Callback<GitHubCounters> callback) {
      request(key).whenComplete((v, t) -> {
        if (t != null)
          callback.onLoadFailure(t);
        else
          callback.onLoadSuccess(v);
      });
  }

  public CompletableFuture<GitHubCounters> request(String key) {
    HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.github.com/repos/" + key))
      .build();
    return client.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
      .thenApply(HttpResponse::body)
      .thenApply(GitHubStatisticsSource::parse);
  }

}

See the project at: https://github.com/sensepitch/badges/blob/master/src/main/java/com/headissue/badges/GitHubStatisticsJava11Source.java

For cache2k 2.0, which can use Java 8 CompletableFuture I intend keep the callback based interface but
add another one so, CompletableFuture can be used directly, thus avoiding boilerplate code like the above that
converts between the different async interfaces.

@cruftex
Copy link
Member Author

cruftex commented Aug 14, 2020

Closing, since coding complete. Unfortunately the commit failed to reference this issue.

@cruftex cruftex closed this as completed Aug 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant