Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java profiling: java.lang.Object.hashCode takes half of the CPU time but never explictly called

I have been benchmarked my multihreaded program using -agentlib:hprof=cpu=samples and was surprised to find the following line in the results:

rank   self  accum   count trace method
   1 52.88% 52.88%    8486 300050 java.lang.Object.hashCode

I never explicitly call hashCode() in my program. What can be the reason for this? How can I understand the source for this time "waste" and whether it is normal or not?

Thanks, David

like image 764
David B Avatar asked Jun 26 '10 16:06

David B


People also ask

When hashCode method is called in Java?

The hashcode() method returns the same hash value when called on two objects, which are equal according to the equals() method. And if the objects are unequal, it usually returns different hash values.

What is hashing and hashCode in Java?

Hashing is a fundamental Computer Science concept which involves mapping objects or entities to integer values. These values are called hash values or hashcodes of those entities. The hashCode() method in Java is used to compute hash values of Java objects.

What is the purpose of the hashCode () method?

The purpose of the hashCode() method is to provide a numeric representation of an object's contents so as to provide an alternate mechanism to loosely identify it. By default the hashCode() returns an integer that represents the internal memory address of the object.


2 Answers

Most likely you're using very intensively a Map such as a HashMap.

HashMap used the hashCode to distribute the objects. If you're using many objects with this data structure, is very important your .equals and your .hashCode method are properly implemented.

See: Effective Java Item 8: Always override hashCode when you override equals

like image 75
OscarRyz Avatar answered Sep 25 '22 21:09

OscarRyz


One thing you should do is to check out matching stack trace to see who is calling it; changes are it is indeed HashMap.

But beyond this, I have noticed that hprof tends to vasty overestimate calls to hashCode(); and I really would like to know how and why. This is based on actually knowing rough performance profile of code; and I have seen 50% percent cpu use (by sampling), where it is all but certain that it absolutely will not take that long. Implementation of hashCode() just returns an int field, and method is final (on final object). So it is basically a profiler artifact of some sort... just no idea how or why, or how to get rid of it.

like image 39
StaxMan Avatar answered Sep 21 '22 21:09

StaxMan