Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does StructuredArray need to be non-constructible?

This talk at 34:00 describes the design of StructuredArrays for Java. Everything's rather clear, except for on thing:

It shouldn't be constructible, i.e., the instance may be only obtainable by some static factory method like newInstance. At the same time, they should be subclassible, which means that there must be a public constructor and the non-constructibility will be assured at runtime. This sounds very hacky, so I wonder why?

I'm aware about the advantages of factories in general and static factory methods in particular. But what do we get here, so that it makes the hack acceptable?

like image 489
maaartinus Avatar asked Mar 07 '26 12:03

maaartinus


1 Answers

The point of the StructuredArray class is that someday it can be replaced with an intrinsic implementation that allocates the whole array, including the component objects, as one long block of memory. When this happens, the size of the object will depend on the number of elements and the element class.

If StructuredArray had a public constructor, then you could write x = new StructuredArray<>(StructuredArray.class, MyElement.class, length). This doesn't seem to present any problem, except that in bytecode, this turns into a new instruction that allocates the object, and then a separate invokespecial instruction to call the object's constructor.

You see the problem -- the new instruction has to allocate the object, but it cannot, because the size of the object depends on constructor parameters (the element class and length) that it doesn't have! Those aren't passed until the constructor call that follows sometime later.

There are ways to around problems like this, but they're all kinda gross. It makes a lot more sense to encapsulate construction in a static factory method, because then you just can't write new StructuredArray..., and the JVM doesn't have to use any "magic" to figure out how much memory to allocate in the new instruction for StructuredArray, because there just can't be any such instructions*.

If some later JVM wants to provide an intrinsic implementation of the static factory that allocates a contiguous array, then it's no problem -- it gets all the information it needs in the factory method invocation.

NB* - yes, OK, technically you can write new StructuredArray..., but it doesn't make a useful object for you.

like image 53
Matt Timmermans Avatar answered Mar 10 '26 01:03

Matt Timmermans