From e23f6461811b97271423df5ae29ac392e2d154e9 Mon Sep 17 00:00:00 2001
From: akwizgran <akwizgran@users.sourceforge.net>
Date: Mon, 28 Nov 2011 15:44:19 +0000
Subject: [PATCH] Cache the return value of Arrays.hashCode().

---
 api/net/sf/briar/api/Bytes.java             | 7 ++++++-
 api/net/sf/briar/api/protocol/UniqueId.java | 7 ++++++-
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/api/net/sf/briar/api/Bytes.java b/api/net/sf/briar/api/Bytes.java
index 77b82c1beb..fe95d75d84 100644
--- a/api/net/sf/briar/api/Bytes.java
+++ b/api/net/sf/briar/api/Bytes.java
@@ -7,6 +7,8 @@ public class Bytes {
 
 	private final byte[] bytes;
 
+	private int hashCode = -1;
+
 	public Bytes(byte[] bytes) {
 		this.bytes = bytes;
 	}
@@ -17,7 +19,10 @@ public class Bytes {
 
 	@Override
 	public int hashCode() {
-		return Arrays.hashCode(bytes);
+		// Thread-safe because if two or more threads check and update the
+		// value, they'll calculate the same value
+		if(hashCode == -1) hashCode = Arrays.hashCode(bytes);
+		return hashCode;
 	}
 
 	@Override
diff --git a/api/net/sf/briar/api/protocol/UniqueId.java b/api/net/sf/briar/api/protocol/UniqueId.java
index 8124ed03f0..5e1e00246d 100644
--- a/api/net/sf/briar/api/protocol/UniqueId.java
+++ b/api/net/sf/briar/api/protocol/UniqueId.java
@@ -9,6 +9,8 @@ public abstract class UniqueId {
 
 	protected final byte[] id;
 
+	private int hashCode = -1;
+
 	protected UniqueId(byte[] id) {
 		assert id.length == LENGTH;
 		this.id = id;
@@ -20,6 +22,9 @@ public abstract class UniqueId {
 
 	@Override
 	public int hashCode() {
-		return Arrays.hashCode(id);
+		// Thread-safe because if two or more threads check and update the
+		// value, they'll calculate the same value
+		if(hashCode == -1) hashCode = Arrays.hashCode(id);
+		return hashCode;
 	}
 }
-- 
GitLab