The offset of the instance property of the String type in memory does not change with the length of the string.

public class A {
  public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    //System.out.println(  ClassLoader.getSystemClassLoader().toString());
    Unsafe unsafe = UnsafeUtil.getUnsafe();
    Person person = new Person();
    long offset = unsafe.objectFieldOffset(person.getClass().getDeclaredField("name1"));
    System.out.println(offset); // 16
    person.setName1("fasfsa321312");
    long offset1 = unsafe.objectFieldOffset(person.getClass().getDeclaredField("name1"));
    System.out.println(offset1);

  }

  private static class Person{
   // private int a;
    private String name;
    private String name1;
   // private static int c;
   // private int b;
    public void setName(String name){
      this.name = name;
    }

    public String getName(String name){
      return this.name;
    }

    public void setName1(String name){
      this.name1 = name;
    }

    public String getName1(String name){
      return this.name1;
    }
  }

  private static class UnsafeUtil {
    private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
      Field field = Unsafe.class.getDeclaredField("theUnsafe");
      field.setAccessible(true);
      return (Unsafe) field.get(null);
    }
  }
}

output result is
16
16

what I want to know is why the memory address does not change when the string changes? Bosses help answer

.
Mar.29,2021


when the object is created, java creates the object in the memory heap and stack respectively, and the changes you make to its properties are all stack-based operations. After the update is finished, the address in the heap will be updated to the heap, and the address in the heap will not change. The memory address is the address of the heap


is my own confusion, and the address stored in the object is the address.

  • A little question about JMM

    < H1 > Hello, everyone. I just watched a video tutorial. I have a question < H1 >. Video tutorial. Is it true to say that stack data can be shared in jmm? I remember that the data in the heap can be shared. Is he wrong? ...

    May.22,2021
Menu