0

If we have the code like this:

class A {
  private hash = 0;

  public void test(){
    if (hash == 1) {
    //dosomething
    }
  }
}

Where exactly the compare performed ?

Here's my understanding:

  1. Load hash into thread's stack, named r1.
  2. compare r1 with literal 1.

Is it right ? In the meaning time, the hash in the heap could be changed ?

WoooHaaaa
  • 19,732
  • 32
  • 90
  • 138
  • I think you are confused. the hash is not the location in the heap, the hash is a value that denotes which objects are unique compared to each other. – greedybuddha May 30 '13 at 02:32
  • @greedybuddha, I'm not sure, but IIRC all instance variables are located in heap, but their values' location may not. – WoooHaaaa May 30 '13 at 02:34
  • The locations are definitely not, there is no way to access the heap location inside of java. – greedybuddha May 30 '13 at 02:36
  • @greedybuddha, check out this [JLS 17.4.1](http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.1) : ** All instance fields, static fields, and array elements are stored in heap memory. ** – WoooHaaaa May 30 '13 at 02:40
  • 1
    I didn't say that they aren't stored in the Heap, they are. I said there is no way to get the Heap addresses. – greedybuddha May 30 '13 at 02:41
  • More likely `hash` is loaded into a register, which is then compared with the literal 1 in a single (maybe 2?) assembly command(s). Also, your example won't compile, it lacks a type on `hash`. – Kevin May 30 '13 at 03:18
  • @greedybuddha Your statement that you can't get heap addresses is correct for primitives, but I believe the default `hashCode()` for `Object`s in Sun's JVM is the address. (And it appears you can use `sun.misc.Unsafe` to get the address regardless of the hash code). – Kevin May 30 '13 at 03:20
  • http://stackoverflow.com/questions/1360826/how-to-get-address-of-a-java-object, from JonSkeet himself... no :). Or if you don't believe him, take a look at the Object code. http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html – greedybuddha May 30 '13 at 03:33

1 Answers1

4

Both field hash and constant 1 are loaded on stack. Then comparison is performed:

 ...
 GETFIELD A.hash : I    // push hash onto the stack
 ICONST_1               // push 1 onto the stack
 IF_ICMPNE L1           // pop the top two ints off the stack and compare them 
 ...                    // do smth
 L1
 RETURN
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275