From 466ac6b703787663e300614033c9fb922b140175 Mon Sep 17 00:00:00 2001 From: Brian Clozel Date: Tue, 25 Feb 2025 16:09:01 +0100 Subject: [PATCH] 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 --- .../cache/interceptor/SimpleKey.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java b/spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java index 760a7f7dbe96..df8055ded476 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java @@ -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"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ * * @author Phillip Webb * @author Juergen Hoeller + * @author Brian Clozel * @since 4.0 * @see SimpleKeyGenerator */ @@ -56,7 +57,7 @@ public SimpleKey(@Nullable Object... elements) { Assert.notNull(elements, "Elements must not be null"); this.params = elements.clone(); // Pre-calculate hashCode field - this.hashCode = Arrays.deepHashCode(this.params); + this.hashCode = calculateHash(this.params); } @@ -79,7 +80,18 @@ public String toString() { private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); // 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); } }