How to Get the Memory Location of a Object in Java

Memory address of variables in Java

That is the class name and System.identityHashCode() separated by the '@' character. What the identity hash code represents is implementation-specific. It often is the initial memory address of the object, but the object can be moved in memory by the VM over time. So (briefly) you can't rely on it being anything.

Getting the memory addresses of variables is meaningless within Java, since the JVM is at liberty to implement objects and move them as it seems fit (your objects may/will move around during garbage collection etc.)

Integer.toBinaryString() will give you an integer in binary form.

How can I get the memory location of a object in java?

This is something you probably don't want to do.

If you really want to do this, something like this code might help:

package test;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class Addresser
{
private static Unsafe unsafe;

static
{
try
{
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
}
catch (Exception e)
{
e.printStackTrace();
}
}

public static long addressOf(Object o)
throws Exception
{
Object[] array = new Object[] {o};

long baseOffset = unsafe.arrayBaseOffset(Object[].class);
int addressSize = unsafe.addressSize();
long objectAddress;
switch (addressSize)
{
case 4:
objectAddress = unsafe.getInt(array, baseOffset);
break;
case 8:
objectAddress = unsafe.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}

return(objectAddress);
}

public static void main(String... args)
throws Exception
{
Object mine = "Hi there".toCharArray();
long address = addressOf(mine);
System.out.println("Addess: " + address);

//Verify address works - should see the characters in the array in the output
printBytes(address, 27);

}

public static void printBytes(long objectAddress, int num)
{
for (long i = 0; i < num; i++)
{
int cur = unsafe.getByte(objectAddress + i);
System.out.print((char)cur);
}
System.out.println();
}
}

But

  • not portable across JVMs or even different versions
  • objects can move because of GC at any time, and cannot synchronize across GCs so results might not make sense
  • not tested across all architectures, endianess, etc. might make this not work everywhere

How to get address of a Java Object?

Firstly - no, you can't get the address of an object in Java; at least, not pure Java with no debugging agent etc. The address can move over time, for one thing. You don't need it.

Secondly, it's slightly hard to follow your explanation but you certainly won't be able to get away without listening for changes to the file itself. Once you've loaded the file into a Properties object, any later changes to the file on disk won't be visible in that object unless you specifically reload it.

Basically you should listen for changes to the file (or poll it) and reload the file (either into a new Properties or overwriting the existing one) at that point. Quite whether you also need to listen for updates on the string container will depend on your application.

How to print address of a variable in Java

There is no element in the java language that allows you the get the address of anything and more importantly there is no language element ever requiring an address for anything. Thats why there is no address-of operator in java. The whole language is designed to work without.

The whole concept of memory address is abstracted in java; the closest you can get is a reference, but that is limited to actual objects. While the reference's value is actually a memory address (or at least something easily convertible into a memory address, see compressed OOPS), there is no way of converting that value to anything else. And again there is no need to ever do this, except maybe for satisfying your curiosity.

It is however possible, by using the (attention: not portable, not meant for actual public use!) java.sun.misc.Unsafe, this class allows converting the value of a reference to a long (representing a memory address). Example for using it can be found here: https://dzone.com/articles/understanding-sunmiscunsafe.

How to get rid of printing object memory location in output in java project with Query, QueryBuilder and Test classes?

Override the toString() method instead of defining a printQuery() method:

@Override
public String toString() {
if (WHERE == null && ORDERBY == null)
return "SELECT " + SELECT + "\nFROM " + FROM + "\n";

if (WHERE == null && ORDERBY != null)
return "SELECT " + SELECT + "\nFROM " + FROM + "\nORDER BY " + ORDERBY + "\n";

if (WHERE != null && ORDERBY == null)
return "SELECT " + SELECT + "\nFROM " + FROM + "\nWHERE " + WHERE + "\n";

if (WHERE != null && ORDERBY != null)
return "SELECT " + SELECT + "\nFROM " + FROM + "\nWHERE " + WHERE + "\nORDER BY " + ORDERBY + "\n";

// should never happen
throw new IllegalStateException("Unhandled case");
}

Role of == operator in Java checking memory address

Well, it's not exactly true that hashCode() always returns the memory address. In your specific case, you are overwriting the function to basically return the hashCode of the Subject reference.

Your evaluate shows the following output:

stringops.Student@955a0720

which might be a bit confusing as this is actually NOT the bare memory address but a call to the toString() method of your object.

Have a look at how Java implements toString:

getClass().getName() + '@' + Integer.toHexString(hashCode())

So, in fact, those two objects have different memory locations, but because you overwrite hashCode() you won't get to see them. Also, there is no way to overwrite how Java selects the memory address of an object (except some hacks maybe), but nevertheless, two objects can't have the same address.

Please include more text instead of screenshots next time to increase searchability of your question for others.

How to print the address of an object if you have redefined toString method

Strictly speaking, you can't print the address of an object in pure Java. The number that looks like an object address in the String produced by Object.toString() is the object's "identity hashcode". It may or may not be related to the object's current address:

  • The specs do not say how the identity hashcode number is calculated. It is deliberately left unspecified.

  • Since the number is a hashcode, it cannot change. So even though it is (typically) related to an object address, that will be the object's address at the time when the hashcode was first accessed. This could be different to its current address, and it will be different if the GC has moved the object since the first time the object's identity hashcode was observed.

  • On a 64bit JVM (with a large enough heap size / not using compressed oops) addresses won't fit into an identity hashcode number which is returned as an int.

Anyhow, the way to get this number is to call System.identityHashCode(obj).


If you really want an object's current address, you can get it using JNI and a native method (and some abstraction breaking), or by using methods in the Unsafe class (see How can I get the memory location of a object in java?). But beware that both of these approaches are non-portable. Also, the object addresses that they give you are liable to "break" when the GC runs which renders them problematic for many (probably most) potential use-cases.


For the doubters, this is what the Java 10 javadocs say on the "hashcode != address" point:

"(The hashCode may or may not be implemented as some function of an object's memory address at some point in time.)"

Emphasis added. Indeed, with recent JVMs, the default algorithm does NOT derive the hashCode from a memory address at all. It has been that way since at least Java 7.

You can confirm this by including -XX:+PrintFlagsFinal in the command line options to find out what the hashcode flag defaults to, and then looking at the OpenJDK source code to see what it means. (The code is in the "vm/runtime/synchronizer.cpp" file in some versions, but YMMV.)



Related Topics



Leave a reply



Submit