Hotspot VM 是如何生成 String oops 和mirror oops 的?

问题描述 投票:0回答:1

在openjdk8源代码中,我发现一些java.lang.String oop不经过字节码引擎并由jvm本身分配。正如

hotspot/src/share/vm/classfile/javaClasses.cpp:185
所说:

Handle java_lang_String::create_from_unicode(jchar* unicode, int length, TRAPS) {
  Handle h_obj = basic_create(length, CHECK_NH); // alloc size of java.lang.String oop
  typeArrayOop buffer = value(h_obj());
  for (int index = 0; index < length; index++) {
    buffer->char_at_put(index, unicode[index]);  // put a char[] into this oop...
  }
  return h_obj;
}

如上所述,创建了一个fake字符串...但是,

java.lang.String
有五个成员变量(字段),它们是如何初始化的?换句话说,这些fake String oop 是如何变成真正的
java.lang.String
对象的?

java.lang.String
相同,
java.lang.Class
也做这个事情。在
hotspot/src/share/vm/classfile/javaClasses.cpp:553
说:

oop java_lang_Class::create_mirror(KlassHandle k, Handle protection_domain, TRAPS) {
    ...
    Handle mirror = InstanceMirrorKlass::cast(SystemDictionary::Class_klass())->allocate_instance(k, CHECK_0);
    ...
    // if `k` holds a InstanceKlass, it will initialize the static fields by constant value attribute. else do nothing...
}

我对此感到非常困惑。只有

alloc
内存,如果是
java.lang.String
的对象,就往里面放一个
char[]
;但是
java.lang.String
java.lang.Class
中的其他字段何时填充到 oop 中?谢谢你。

java jvm jvm-hotspot
1个回答
2
投票

java_lang_String::basic_create()
分配
String
对象并初始化其
value
字段:

    obj = InstanceKlass::cast(SystemDictionary::String_klass())->allocate_instance(CHECK_NH);

    // Create the char array.  The String object must be handlized here
    // because GC can happen as a result of the allocation attempt.
    Handle h_obj(THREAD, obj);
    typeArrayOop buffer;
      buffer = oopFactory::new_charArray(length, CHECK_NH);

    // Point the String at the char array
    obj = h_obj();
    set_value(obj, buffer);   <<<--- char[] value is set here
  // No need to zero the offset, allocation zero'ed the entire String object
  assert(offset(obj) == 0, "initial String offset should be zero");
//set_offset(obj, 0);
  set_count(obj, length);

hash
字段是延迟计算的。在分配时,它具有默认值
0
,因为
allocate_instance
会清除整个对象。 JDK 8 中没有其他
String
实例字段。

至于

java.lang.Class
,它没有在分配时初始化的字段,因为它的所有字段都是缓存。当需要时,它们在 Java 代码中设置。同样,整个
Class
实例被分配例程清零。

© www.soinside.com 2019 - 2024. All rights reserved.