Fwd: Proposal: Static/final constructors for bucket-3 primitive classes.
Brian Goetz
brian.goetz at oracle.com
Sun Dec 5 18:36:05 UTC 2021
The following was received on valhalla-spec-comments.
Summary: Various syntax options for no-arg constructors of "bucket 3"
primitives, to enable users to pick a default value other than zero.
Analysis: The suggestion is well-intentioned, but it is built on some
significant misunderstandings of the problem we are facing.
It assumes that it is sensible to allow a non-zero default value of a
primitive to be specified by the class declaration. While it is
entirely understandable why one would want this, the problem is not that
there isn't a good syntax for it (there obviously is), nor that running
the constructor multiple times is the problem -- it is deeper than
that. Numerous safety properties derive from the fact that newly
allocated objects and arrays are bulk-initialized to zero; compromising
this seems likely to lead to exploits.
-------- Forwarded Message --------
Subject: Proposal: Static/final constructors for bucket-3 primitive
classes.
Date: Fri, 3 Dec 2021 21:15:50 -0600
From: Clement Cherlin <clement.cherlin at gmail.com>
To: valhalla-spec-comments at openjdk.java.net
Motivation: A concern with primitive classes (bucket 3) is that the
all-zeroes default value may be inappropriate or even invalid in some
cases. This proposal suggests a language enhancement to give primitive
class authors control over the default value of their class without,
in most cases, requiring a constructor call to create an instance.
Proposed language change:
Primitive classes can apply either the keyword "static" or the
keyword "final", but not both, to their no-argument constructor.
A "final" no-arg constructor is evaluated once, at compile time. The
constructed object is treated as a static final constant, and can be
folded as a constant, or copied verbatim whenever a default value of
that class is instantiated.
A "static" no-arg constructor is evaluated once, when the class is loaded.
The
constructed object is copied verbatim whenever a default value of that
class is instantiated.
Justification:
Presuming that non-zero default values need to exist, and we're going
to be constructing lots and lots of primitive objects and arrays of
primitive objects, it behooves us to make initialization of default
values as efficient as possible. Much of the time, there will be no
need to call a constructor / factory method, just make a copy of a
pre-existing default value (perhaps lazily).
Related work:
For classes without sensible default values, I have another proposal I
am working on to make initializing arrays of primitive objects possible
and efficient, without resorting to the all-zeroes default.
Cheers,
Clement Cherlin
More information about the valhalla-spec-observers
mailing list