AtomicScala / atomic-scala-corrections

Find out about or report corrections for the book "Atomic Scala"
http://www.atomicscala.com
6 stars 2 forks source link

println(obj) prints hash code, not object's memory location #31

Open mb720 opened 9 years ago

mb720 commented 9 years ago

Thank you very much for your great book.

In atom "Creating Classes" on page 88 and 89 it reads:

The part before the ‘@’ is the class name, and the number (yes, that’s a number even though it includes some letters – it’s called “hexadecimal notation” and you can learn about it in Wikipedia) indicates the address where the object is located in your computer’s memory.

I think the text I emphasized is not true. println(obj) calls obj.hashCode() if the object is not null. For the HotSpot implementation of the JVM for JDK 8 this means a call to os::random per default. Thus, the part after the @ has nothing to do with the object's memory location (which would lead to an ever-changing result of hashCode() because the JVM moves around objects in memory).

I'd propose changing the relevant text to something like "... and the number (...) is a random identifier for the object."

BruceEckel commented 9 years ago

Interesting -- what you say seems like it should be true, especially considering that some garbage-collection algorithms move objects around.

However, if you follow the link you gave me in your issue post, you'll see (bottom of the original post): image

And if you follow the link given, http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html, you'll see that it says just that: image

mb720 commented 9 years ago

Hi,

Thank you for your answer; The documentation is without a doubt quite clear on this.

I sent javasedocs_us@oracle.com an email regarding this more than three weeks ago. Didn't get a response, though.

My argumentation for Object's hash code being a random number is as follows: This leads me to the implementation of hashCode() in HotSpot; When I look at it, I see a call to os::random but nothing related to a memory address:

static inline intptr_t get_next_hash(Thread * Self, oop obj) {
  intptr_t value = 0 ;
  if (hashCode == 0) {
     // This form uses an unguarded global Park-Miller RNG,
     // so it's possible for two threads to race and generate the same RNG.
     // On MP system we'll have lots of RW access to a global, so the
     // mechanism induces lots of coherency traffic.
     value = os::random() ;
  }...

Kind regards, Matthias