Skip to content

Commit 466ac6b

Browse files
committed
Improve SimpleKey hashing function
Prior to this commit, `SimpleKey` would be used in Spring Framework's caching support and its `hashCode` value would be used to efficiently store this key in data structures. While the current hashcode strategy works, the resulting values don't spread well enough when input keys are sequential (which is often the case). This can have negative performance impacts, depending on the data structures used by the cache implementation. This commit improves the `hashCode` function with a mixer to better spread the hash values. This is using the mixer function from the MurMur3 hash algorithm. Closes gh-34483
1 parent 8b14bf8 commit 466ac6b

File tree

1 file changed

+15
-3
lines changed
  • spring-context/src/main/java/org/springframework/cache/interceptor

1 file changed

+15
-3
lines changed

spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -30,6 +30,7 @@
3030
*
3131
* @author Phillip Webb
3232
* @author Juergen Hoeller
33+
* @author Brian Clozel
3334
* @since 4.0
3435
* @see SimpleKeyGenerator
3536
*/
@@ -56,7 +57,7 @@ public SimpleKey(@Nullable Object... elements) {
5657
Assert.notNull(elements, "Elements must not be null");
5758
this.params = elements.clone();
5859
// Pre-calculate hashCode field
59-
this.hashCode = Arrays.deepHashCode(this.params);
60+
this.hashCode = calculateHash(this.params);
6061
}
6162

6263

@@ -79,7 +80,18 @@ public String toString() {
7980
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
8081
ois.defaultReadObject();
8182
// Re-calculate hashCode field on deserialization
82-
this.hashCode = Arrays.deepHashCode(this.params);
83+
this.hashCode = calculateHash(this.params);
84+
}
85+
86+
/**
87+
* Calculate the hash of the key using its elements and
88+
* mix the result with the finalising function of MurmurHash3.
89+
*/
90+
private static int calculateHash(@Nullable Object[] params) {
91+
int hash = Arrays.deepHashCode(params);
92+
hash = (hash ^ (hash >>> 16)) * 0x85ebca6b;
93+
hash = (hash ^ (hash >>> 13)) * 0xc2b2ae35;
94+
return hash ^ (hash >>> 16);
8395
}
8496

8597
}

0 commit comments

Comments
 (0)