From ba86e3968c452aa12efbb618c176be50b02bd433 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Fri, 2 Oct 2015 16:16:18 -0400 Subject: [PATCH] Use a cloned instance of MessageDigest This commit adds a micro-optimization for obtaining a MessageDigest instance for calculating SHA-256 message digests. Benchmarking with JMH showed the micro-benchmarking of getting new instances versus cloning existing instances to be around twice as slow. Original commit: elastic/x-pack-elasticsearch@d558ed961f526720f9203f3ea23fe9183b0ec220 --- .../renderer/cluster/ClusterInfoRenderer.java | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/marvel/src/main/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoRenderer.java b/marvel/src/main/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoRenderer.java index cb685741855..d723f7b3093 100644 --- a/marvel/src/main/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoRenderer.java +++ b/marvel/src/main/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoRenderer.java @@ -22,6 +22,28 @@ import java.util.List; public class ClusterInfoRenderer extends AbstractRenderer { + static final class MessageDigestSHA256Provider { + private static final MessageDigest digest; + + static { + try { + digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new ElasticsearchException("Unexpected exception creating MessageDigest instance", e); + } + } + + private static MessageDigest sha256() { + try { + MessageDigest sha = (MessageDigest) digest.clone(); + sha.reset(); + return sha; + } catch (CloneNotSupportedException e) { + throw new ElasticsearchException("Unexpected exception creating MessageDigest instance", e); + } + } + } + public ClusterInfoRenderer() { super(null, false); } @@ -67,15 +89,14 @@ public class ClusterInfoRenderer extends AbstractRenderer public static String hash(String licenseStatus, String licenseUid, String licenseType, String licenseExpiryDate, String clusterUUID) { String toHash = licenseStatus + licenseUid + licenseType + licenseExpiryDate + clusterUUID; try { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - byte[] sha256Bytes = md.digest(toHash.getBytes("UTF-8")); + byte[] sha256Bytes = MessageDigestSHA256Provider.sha256().digest(toHash.getBytes("UTF-8")); StringBuffer hash = new StringBuffer(); for (int i = 0; i < sha256Bytes.length; i++) { hash.append(Integer.toHexString(0xff & sha256Bytes[i])); } return hash.toString(); - } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { - throw new ElasticsearchException("Unexpected error computing SHA-256 hash", e); + } catch (UnsupportedEncodingException e) { + throw new ElasticsearchException("Unexpected error calculating SHA-256 MessageDigest", e); } }