1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.buildcache.hash;
20
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
23 import java.util.Objects;
24
25
26
27
28 public class ThreadLocalDigest {
29
30 public static MessageDigest get(ThreadLocal<MessageDigest> local, String algorithm) {
31 final MessageDigest digest = local.get();
32 if (digest == null) {
33 return create(local, algorithm);
34 }
35
36 if (Objects.equals(digest.getAlgorithm(), algorithm)) {
37 return reset(digest);
38 }
39
40 reset(digest);
41 return create(local, algorithm);
42 }
43
44 private static MessageDigest create(ThreadLocal<MessageDigest> local, String algorithm) {
45 try {
46 final MessageDigest digest = MessageDigest.getInstance(algorithm);
47 local.set(digest);
48 return digest;
49 } catch (NoSuchAlgorithmException e) {
50 throw new RuntimeException("Cannot create message digest with algorithm: " + algorithm, e);
51 }
52 }
53
54 private static MessageDigest reset(MessageDigest digest) {
55 digest.reset();
56 return digest;
57 }
58
59 private ThreadLocalDigest() {}
60 }