CacheBuilder.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package io.opentelemetry.instrumentation.api.caching;
  6. import java.util.concurrent.Executor;
  7. import javax.annotation.Nullable;
  8. /** A builder of {@link Cache}. */
  9. public final class CacheBuilder {
  10. private static final long UNSET = -1;
  11. private static final boolean USE_CAFFEINE_3 = Caffeine3Cache.available();
  12. private boolean weakKeys;
  13. private boolean weakValues;
  14. private long maximumSize = UNSET;
  15. @Nullable private Executor executor = null;
  16. /** Sets the maximum size of the cache. */
  17. public CacheBuilder setMaximumSize(long maximumSize) {
  18. this.maximumSize = maximumSize;
  19. return this;
  20. }
  21. /**
  22. * Sets that keys should be referenced weakly. If used, keys will use identity comparison, not
  23. * {@link Object#equals(Object)}.
  24. */
  25. public CacheBuilder setWeakKeys() {
  26. this.weakKeys = true;
  27. return this;
  28. }
  29. /** Sets that values should be referenced weakly. */
  30. public CacheBuilder setWeakValues() {
  31. this.weakValues = true;
  32. return this;
  33. }
  34. // Visible for testing
  35. CacheBuilder setExecutor(Executor executor) {
  36. this.executor = executor;
  37. return this;
  38. }
  39. /** Returns a new {@link Cache} with the settings of this {@link CacheBuilder}. */
  40. public <K, V> Cache<K, V> build() {
  41. if (weakKeys && !weakValues && maximumSize == UNSET) {
  42. return new WeakLockFreeCache<>();
  43. }
  44. CaffeineCache.Builder<K, V> caffeine =
  45. USE_CAFFEINE_3 ? new Caffeine3Cache.Builder<>() : new Caffeine2Cache.Builder<>();
  46. if (weakKeys) {
  47. caffeine.weakKeys();
  48. }
  49. if (weakValues) {
  50. caffeine.weakValues();
  51. }
  52. if (maximumSize != UNSET) {
  53. caffeine.maximumSize(maximumSize);
  54. }
  55. if (executor != null) {
  56. caffeine.executor(executor);
  57. } else {
  58. caffeine.executor(Runnable::run);
  59. }
  60. return caffeine.build();
  61. }
  62. CacheBuilder() {}
  63. }