Skip to content

Commit

Permalink
Update clone() failure message. Move to LinkedBlockingDeque for Diges…
Browse files Browse the repository at this point in the history
…tAlgorithm cache.
  • Loading branch information
millems committed Jan 29, 2025
1 parent 18f00ca commit 03d0084
Showing 1 changed file with 8 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.SdkAutoCloseable;
Expand All @@ -33,7 +33,7 @@ public enum DigestAlgorithm {

private static final int MAX_CACHED_DIGESTS = 10_000;
private final String algorithmName;
private final Deque<MessageDigest> digestCache = new ConcurrentLinkedDeque<>(); // Used as LIFO for cache-friendliness
private final Deque<MessageDigest> digestCache = new LinkedBlockingDeque<>(MAX_CACHED_DIGESTS); // LIFO

DigestAlgorithm(String algorithmName) {
this.algorithmName = algorithmName;
Expand Down Expand Up @@ -91,6 +91,7 @@ public byte[] digest() {
return messageDigest;
}
messageDigest = messageDigest().digest();
close();
return messageDigest;
}

Expand All @@ -103,20 +104,18 @@ public void close() {
return;
}

// Avoid over-caching after large traffic bursts. The maximum chosen here is arbitrary. It's also not strictly
// enforced, since these statements aren't synchronized.
if (digestCache.size() <= MAX_CACHED_DIGESTS) {
digestCache.addFirst(digest.get());
}
// Drop this digest is the cache is full.
digestCache.offerFirst(digest.get());

digest = closedDigest;
}

@Override
public CloseableMessageDigest clone() {
try {
return new CloseableMessageDigest((MessageDigest) digest.get().clone());
} catch (CloneNotSupportedException e) { // should never occur
throw new IllegalStateException("unexpected", e);
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Clone was not supported by this digest type.", e);
}
}
}
Expand Down

0 comments on commit 03d0084

Please sign in to comment.