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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -