Hi all,
i've plyed for some quite times now to specify in my mind what a value based 
class can be and i think it's time write that down.

First, why we need value based class ?
We want to offer a path to refactor a class to a value type but given that 
class instances are nullable and value type values are not, the proposed 
solution is to introduce a kind of 'compatible with null' value type i.e. a 
value based class. Java in its API already specifies that some classess 
(Optional, LocalDateTime) are value based classes saying that they have no 
identity.

What is the best outcome ?
The best case is like checked exceptions, i.e. the VM doesn't know what a value 
based class is and only javac knows what a value based class is and add some 
magics, do null tranlation back and forth. But i doubt it's possible because 
with the ValueTypes attribute, a class can not be a reference class and as a 
value type inside the same method, so the VM has to do the conversion in 
adapters.

Proposed wrapping/unwrapping:
A value based class is a value type with one discriminator field. A 
discriminator field is a field that is annotated with the flag 
ACC_DISCRIMINATOR (only one by value based class). Technically from the VM 
implementation point of view, a discriminator is a field_offset + a type.

  class     -> value type
  if (null) -> vdefault

  value type                         -> class
  if (vt[discriminator_offset] == 0) -> null


The Value Type attributes also need to be modified to include a boolean that 
says if it's a plain value type or a value based class.

By example, for java.util.Optional, the field that contains the reference is 
also the discriminator field, which means that the difference Optional as value 
type and Optional as value based class is that the interpreter and the JIT may 
have to execute more tests to do null wrapping/unwrapping.

For java.util.OptionalLong, here we need a supplementary field, a boolean (a 
byte), is enough. In that case, the value based class may take more space + 
more tests.

For the class of java.time, Stephen can choose on per class basis, how to null 
as to be encoded.


To summarize:
A value based class can be either a class with some JIT optimizations but the 
layout of a class or a value type with a way to encode null, i think the former 
solution is sad.
Obviously, i'm not a specialist of the assembly languages so there is maybe 
another encoding scheme.
I think that letting the user to specify the discriminator field solve the 
issue to have to come with a general scheme that works for all value based 
classes, because you offload the verification that the discriminator can not be 
zero in the normal case to the user.

Rémi

Reply via email to