在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;
}
如上所述,创建了一个假字符串...但是,java.lang.String
有五个成员变量(字段),它们是如何初始化的?换句话说,这些假 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_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
实例通过分配例程归零。
关于java - Hotspot VM 如何生成字符串oops 和镜像oops?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47299280/