Browse Source

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
pull/34492/head
Brian Clozel 10 months ago
parent
commit
466ac6b703
  1. 18
      spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java

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

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2025 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,6 +30,7 @@ import org.springframework.util.Assert;
* *
* @author Phillip Webb * @author Phillip Webb
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Brian Clozel
* @since 4.0 * @since 4.0
* @see SimpleKeyGenerator * @see SimpleKeyGenerator
*/ */
@ -56,7 +57,7 @@ public class SimpleKey implements Serializable {
Assert.notNull(elements, "Elements must not be null"); Assert.notNull(elements, "Elements must not be null");
this.params = elements.clone(); this.params = elements.clone();
// Pre-calculate hashCode field // Pre-calculate hashCode field
this.hashCode = Arrays.deepHashCode(this.params); this.hashCode = calculateHash(this.params);
} }
@ -79,7 +80,18 @@ public class SimpleKey implements Serializable {
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject(); ois.defaultReadObject();
// Re-calculate hashCode field on deserialization // Re-calculate hashCode field on deserialization
this.hashCode = Arrays.deepHashCode(this.params); this.hashCode = calculateHash(this.params);
}
/**
* Calculate the hash of the key using its elements and
* mix the result with the finalising function of MurmurHash3.
*/
private static int calculateHash(@Nullable Object[] params) {
int hash = Arrays.deepHashCode(params);
hash = (hash ^ (hash >>> 16)) * 0x85ebca6b;
hash = (hash ^ (hash >>> 13)) * 0xc2b2ae35;
return hash ^ (hash >>> 16);
} }
} }

Loading…
Cancel
Save