Kai Shen wrote:After a few minus of struggling, I gave up and he told me the answer is to synchronized hashcode method. I can't think this through. I thought hashcode returns int, it doesn't make much sense to lock a int, right?
Well, you wouldn't be locking an int, you'd be locking the instance that's being used as the key. But the interviewer's answer really doesn't make sense. For one thing, this would offer no protection against two instances that were equal, but were still different instances. Also the time to update an element in a HashMap is greater than the time required to call hashCode(), so even if hashCode()
were an exclusive operation, there would still be a possibility of the HashMap being updated by two different threads, for the same key, at the same time,
outside of the call to hashCode().
I would say the correct answer to that question was to use ConcurrentHashMap, and the interviewer deserves a slap on the head for thinking his "clever" solution would be better than the standard library solution. Do not trust this interviewer; he doesn't know what he's doing.