• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ben-manes / caffeine / #5612

11 Jul 2026 03:47PM UTC coverage: 71.292% (-28.7%) from 100.0%
#5612

push

github

ben-manes
Preserve timestamps on a raced same-instance refresh

The automatic refreshIfNeeded path checked for an equal-value reload
before the ABA/ownership check and returned without preserving the
timestamps, so a reload completing after a concurrent put(k,
sameInstance) did a full update — shifting the entry's expiration
forward by the reload's in-flight duration and stomping the write.
Mirror the explicit-refresh fix: check ownership first. An owned
reload installs the value (refreshing metadata even for a same
instance), while a raced reload preserves the write's timestamps and
only notifies REPLACED when the value differs.

2957 of 4134 branches covered (71.53%)

3 of 3 new or added lines in 1 file covered. (100.0%)

2408 existing lines in 53 files now uncovered.

5980 of 8388 relevant lines covered (71.29%)

0.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.44
/caffeine/src/main/java/com/github/benmanes/caffeine/cache/Async.java
1
/*
2
 * Copyright 2015 Ben Manes. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package com.github.benmanes.caffeine.cache;
17

18
import static com.github.benmanes.caffeine.cache.BoundedLocalCache.MAXIMUM_EXPIRY;
19
import static java.util.Objects.requireNonNull;
20

21
import java.io.Serializable;
22
import java.lang.System.Logger;
23
import java.lang.System.Logger.Level;
24
import java.util.concurrent.CancellationException;
25
import java.util.concurrent.CompletableFuture;
26
import java.util.concurrent.CompletionException;
27
import java.util.concurrent.Executor;
28

29
import org.jspecify.annotations.Nullable;
30

31
/**
32
 * Static utility methods and classes pertaining to asynchronous operations.
33
 *
34
 * @author ben.manes@gmail.com (Ben Manes)
35
 */
36
@SuppressWarnings("serial")
37
final class Async {
38
  static final long ASYNC_EXPIRY = (Long.MAX_VALUE >> 1) + (Long.MAX_VALUE >> 2); // 220 years
39
  static final Logger logger = System.getLogger(Async.class.getName());
1✔
40

41
  private Async() {}
42

43
  /** Returns if the future has successfully completed with a non-null value. */
44
  static boolean isReady(@Nullable CompletableFuture<?> future) {
45
    return getIfReady(future) != null;
1✔
46
  }
47

48
  /** Returns the current value or null if either not done or failed. */
49
  static <V> @Nullable V getIfReady(@Nullable CompletableFuture<V> future) {
50
    return ((future != null) && future.isDone() && !future.isCompletedExceptionally())
1✔
51
        ? future.join()
1✔
52
        : null;
1✔
53
  }
54

55
  /** Returns the value when completed successfully or null if failed. */
56
  static <V> @Nullable V getWhenSuccessful(@Nullable CompletableFuture<V> future) {
57
    try {
58
      return (future == null) ? null : future.join();
1✔
59
    } catch (CancellationException | CompletionException e) {
1✔
60
      return null;
1✔
61
    }
62
  }
63

64
  /**
65
   * A removal listener that asynchronously forwards the value stored in a {@link CompletableFuture}
66
   * if successful to the user-supplied removal listener.
67
   */
68
  static final class AsyncRemovalListener<K, V>
69
      implements RemovalListener<K, CompletableFuture<@Nullable V>>, Serializable {
70
    private static final long serialVersionUID = 1L;
71

72
    final RemovalListener<K, V> delegate;
73
    final Executor executor;
74

75
    AsyncRemovalListener(RemovalListener<K, V> delegate, Executor executor) {
1✔
76
      this.delegate = requireNonNull(delegate);
1✔
77
      this.executor = requireNonNull(executor);
1✔
78
    }
1✔
79

80
    @Override
81
    @SuppressWarnings("FutureReturnValueIgnored")
82
    public void onRemoval(@Nullable K key,
83
        @Nullable CompletableFuture<@Nullable V> future, RemovalCause cause) {
84
      if (future != null) {
1!
85
        future.thenAccept(value -> {
1✔
86
          if (value != null) {
1✔
87
            Runnable task = () -> {
1✔
88
              try {
89
                delegate.onRemoval(key, value, cause);
1✔
90
              } catch (Throwable t) {
1✔
91
                logger.log(Level.WARNING, "Exception thrown by removal listener", t);
1✔
92
              }
1✔
93
            };
1✔
94
            try {
95
              executor.execute(task);
1✔
96
            } catch (Throwable t) {
1✔
97
              logger.log(Level.ERROR, "Exception thrown when submitting removal listener", t);
1✔
98
              task.run();
1✔
99
            }
1✔
100
          }
101
        });
1✔
102
      }
103
    }
1✔
104

105
    Object writeReplace() {
106
      return delegate;
1✔
107
    }
108
  }
109

110
  /**
111
   * An eviction listener that forwards the value stored in a {@link CompletableFuture} to the
112
   * user-supplied eviction listener.
113
   */
114
  static final class AsyncEvictionListener<K, V>
115
      implements RemovalListener<K, CompletableFuture<V>>, Serializable {
116
    private static final long serialVersionUID = 1L;
117

118
    final RemovalListener<K, V> delegate;
119

120
    AsyncEvictionListener(RemovalListener<K, V> delegate) {
1✔
121
      this.delegate = requireNonNull(delegate);
1✔
122
    }
1✔
123

124
    @Override
125
    public void onRemoval(@Nullable K key,
126
        @Nullable CompletableFuture<V> future, RemovalCause cause) {
127
      // Must have been completed and be non-null to be eligible for eviction
128
      V value = Async.getIfReady(future);
1✔
129
      if (value != null) {
1!
130
        delegate.onRemoval(key, value, cause);
1✔
131
      }
132
    }
1✔
133

134
    Object writeReplace() {
135
      return delegate;
1✔
136
    }
137
  }
138

139
  /**
140
   * A weigher for asynchronous computations. When the value is being loaded this weigher returns
141
   * {@code 0} to indicate that the entry should not be evicted due to a size constraint. If the
142
   * value is computed successfully then the entry must be reinserted so that the weight is updated
143
   * and the expiration timeouts reflect the value once present. This can be done safely using
144
   * {@link java.util.Map#replace(Object, Object, Object)}.
145
   */
146
  static final class AsyncWeigher<K, V> implements Weigher<K, CompletableFuture<V>>, Serializable {
147
    private static final long serialVersionUID = 1L;
148

149
    final Weigher<K, V> delegate;
150

151
    AsyncWeigher(Weigher<K, V> delegate) {
1✔
152
      this.delegate = requireNonNull(delegate);
1✔
153
    }
1✔
154

155
    @Override
156
    public int weigh(K key, CompletableFuture<V> future) {
157
      V value = getIfReady(future);
1✔
158
      return (value == null) ? 0 : delegate.weigh(key, value);
1✔
159
    }
160

161
    Object writeReplace() {
162
      return delegate;
1✔
163
    }
164
  }
165

166
  /**
167
   * An expiry for asynchronous computations. When the value is being loaded this expiry returns
168
   * {@code ASYNC_EXPIRY} to indicate that the entry should not be evicted due to an expiry
169
   * constraint. If the value is computed successfully then the entry must be reinserted so that the
170
   * expiration is updated and the expiration timeouts reflect the value once present. The
171
   * duration's maximum range is reserved to coordinate with the asynchronous life cycle.
172
   */
173
  static final class AsyncExpiry<K, V> implements Expiry<K, CompletableFuture<V>>, Serializable {
174
    private static final long serialVersionUID = 1L;
175

176
    final Expiry<? super K, ? super V> delegate;
177

178
    AsyncExpiry(Expiry<? super K, ? super V> delegate) {
1✔
179
      this.delegate = requireNonNull(delegate);
1✔
180
    }
1✔
181

182
    @Override
183
    public long expireAfterCreate(K key, CompletableFuture<V> future, long currentTime) {
184
      V value = getIfReady(future);
1✔
185
      if (value != null) {
1✔
186
        long duration = delegate.expireAfterCreate(key, value, currentTime);
1✔
187
        return Math.min(duration, MAXIMUM_EXPIRY);
1✔
188
      }
189
      return ASYNC_EXPIRY;
1✔
190
    }
191

192
    @Override
193
    public long expireAfterUpdate(K key, CompletableFuture<V> future,
194
        long currentTime, long currentDuration) {
195
      V value = getIfReady(future);
1✔
196
      if (value != null) {
1✔
197
        long duration = (currentDuration > MAXIMUM_EXPIRY)
1✔
198
            ? delegate.expireAfterCreate(key, value, currentTime)
1✔
199
            : delegate.expireAfterUpdate(key, value, currentTime, currentDuration);
1✔
200
        return Math.min(duration, MAXIMUM_EXPIRY);
1✔
201
      }
202
      return ASYNC_EXPIRY;
1✔
203
    }
204

205
    @Override
206
    public long expireAfterRead(K key, CompletableFuture<V> future,
207
        long currentTime, long currentDuration) {
208
      V value = getIfReady(future);
1✔
209
      if (value != null) {
1!
210
        long duration = delegate.expireAfterRead(key, value, currentTime, currentDuration);
1✔
211
        return Math.min(duration, MAXIMUM_EXPIRY);
1✔
212
      }
UNCOV
213
      return ASYNC_EXPIRY;
×
214
    }
215

216
    Object writeReplace() {
217
      return delegate;
1✔
218
    }
219
  }
220
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc