Hi, developers,
I have a few questions / proposals about the design of JEP 500.

$$ Serialize classes implementing the Serializable interface
JEP 500 claims that
```
Rather than ask users to enable final field mutation on the command
line, maintainers of serialization libraries should serialize and
deserialize objects using the sun.reflect.ReflectionFactory API, which
is supported for this purpose. This API allows a serialization library
to obtain a method handle to special code that initializes an object
by assigning to its instance fields directly, including final fields.
This code, which is dynamically generated by the JDK, gives the
serialization library the same powers as the JDK's own serialization
facilities; it is not necessary to enable final field mutation by the
module of the serialization library.
```

However, after carefully viewing all API exposed in
sun.reflect.ReflectionFactory, I failed to find such an API to
allocate an object instance while assigning all its final fields.
Perhaps it is because I'm not familiar with Java Serializable API, or
due to lack of documents.

$$ Serialize other classes

Before JEP 500, the only way to do so was to
1. use sun.misc.Unsafe#allocateInstance to create an instance, and
2. invoke memory access methods to assign values to final fields.
However, after JEP 500, #2 is considered as an illegal operation,
which is no longer available once mutation to final fields are
disabled by default.

What I'm expecting is an API inside MethodHandles.Lookup that performs
permission checks and returns a special MethodHandle.
This MethodHandle should accept a number of arguments and
1. allocate an instance of the specific type, and
2. use privileged internal ways to assign values to final fields, from
the MethodHandle's arguments, and
3. publish the object (like what the Valhalla project called
'Non-Larval State'), which prevents any future final fields mutation
and
4. return the newly-allocated object.

For application developers, this new API can enable Serialization
Libraries (like gson) to create objects without forcing users to make
all their legacy codes implement the Serialization interface, which
maintains compatibility with legacy codes.
For JVM, this new API doesn't involve any mutation to final fields, so
JVM could still consider 'final' as real final.

However, there're a couple of risks / problems.
1. Whether 'allocate an instance of the specific type' should invoke
any constructors or directly create an object like
Unsafe#allocateInstance,
2. Serializing any object is extremely dangerous, as the field's value
can't be verified by guards in class constructors.
3. ...

Thank you.
> Sorry for any incorrect statement in this email in advance as I'm not a 
> native speaker of English and I'm new in OpenJDK maillist.

Reply via email to