java - Thread-safe lazy initialization -
i've read thread-safe lazy initialization , @ implementation of hashcode method in string class. apparently method thread-safe, made own version of class (immutable).
private int hashcode; @override public int hashcode() { int h = hashcode; if (h == 0 && array.length > 0) { hashcode = (h = arrays.hashcode(array)); } return h; }
my question : thread-safe ? don't understand why. not see prevents thread enter method while still inside, maybe got wrong.
as @jb nizet pointed out, main problem have non-empty array hash happens 0
. need able distinguish "hash 0" "hash unknown". use nullable integer
this:
private final atomicreference<integer> hashcode = new atomicreference<>(); @override public int hashcode() { integer h = hashcode.get(); if (h != null) return h; int computedhash = arrays.hashcode(array); hashcode.compareandset(null, computedhash); return computedhash; }
Comments
Post a Comment