Skip to content

Commit a476ec5

Browse files
committed
8292983: ModuleReferenceImpl.computeHash should record algorithm for cache checks
Reviewed-by: alanb, mchung, jpai
1 parent 99cab6a commit a476ec5

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java

+16-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -62,8 +62,11 @@ public class ModuleReferenceImpl extends ModuleReference {
6262
// ModuleResolution flags
6363
private final ModuleResolution moduleResolution;
6464

65-
// cached hash of this module to avoid needing to compute it many times
66-
private byte[] cachedHash;
65+
// Single-slot cache of this module's hash to avoid needing to compute
66+
// it many times. For correctness under concurrent updates, we need to
67+
// wrap the fields updated at the same time with a record.
68+
private record CachedHash(byte[] hash, String algorithm) {}
69+
private CachedHash cachedHash;
6770

6871
/**
6972
* Constructs a new instance of this class.
@@ -139,13 +142,17 @@ public ModuleResolution moduleResolution() {
139142
* @throws java.io.UncheckedIOException if an I/O error occurs
140143
*/
141144
public byte[] computeHash(String algorithm) {
142-
byte[] result = cachedHash;
143-
if (result != null)
144-
return result;
145-
if (hasher == null)
145+
CachedHash ch = cachedHash;
146+
if (ch != null && ch.algorithm().equals(algorithm)) {
147+
return ch.hash();
148+
}
149+
150+
if (hasher == null) {
146151
return null;
147-
cachedHash = result = hasher.generate(algorithm);
148-
return result;
152+
}
153+
byte[] hash = hasher.generate(algorithm);
154+
cachedHash = new CachedHash(hash, algorithm);
155+
return hash;
149156
}
150157

151158
@Override

0 commit comments

Comments
 (0)