Cache the return value of Arrays.hashCode().

This commit is contained in:
akwizgran
2011-11-28 15:44:19 +00:00
parent b72a90be21
commit e23f646181
2 changed files with 12 additions and 2 deletions

View File

@@ -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

View File

@@ -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;
}
}