Static fields in specialized classes
Remi Forax
forax at univ-mlv.fr
Thu Oct 16 09:58:06 UTC 2014
On 10/15/2014 04:37 PM, Brian Goetz wrote:
> Actually we're all being silly. Referencing the field at all will
> trigger initialization. No extra kicking needed.
>
> So if we have:
>
> class Foo<any T> {
> static int x = 3;
>
> void foo() { ... x ... }
> }
>
> the reference to Foo.x in Foo<int> will trigger initialization of Foo,
> causing its static initializers to run.
yes, but not at the right time :(
class Foo<any T> {
static int x;
static {
System.out.println("init");
x = 2;
}
void foo() {
System.out.println("foo");
... x ...
}
}
new Foo<int>().foo()
will print "foo" then "init" instead of "init" then "foo".
Rémi
>
> On 10/15/2014 7:14 AM, Remi Forax wrote:
>>
>> On 10/15/2014 12:22 PM, Paul Sandoz wrote:
>>> On Oct 14, 2014, at 11:45 PM, Brian Goetz <brian.goetz at Oracle.COM>
>>> wrote:
>>>
>>>>> - care might need to be taken with class initlization, static access
>>>>> should trigger initialisation before that access occurs but does this
>>>>> mean both Foo and Foo<int> should be initialized if access occurs
>>>>> from the latter? (not sure if you already have this aspect covered)
>>>> I think we have this one covered. The compiler and specializer
>>>> cooperate to have this effect.
>>>>
>>>> - All declarations of static members (fields and methods, including
>>>> <clinit>) are stripped out during specialization. So the static
>>>> members exist only on the template (base) class.
>>>>
>>>> - All references to static members (whether through classes or
>>>> through instances) are rewritten to directly reference the template
>>>> class.
>>>>
>>>> - Specialized classes acquire a <clinit> that does "LDC
>>>> template.class", idempotently forcing the template class to be
>>>> initialized if it is not already.
>>>>
>>> I am not sure an LDC is sufficient to guarantee initialization of the
>>> template class. See example program below.
>>
>> No, it doesn't.
>> LDC do load the class but the VM is not required to trigger the class
>> initialisation.
>>
>>>
>>> It may be necessary to invoke UNSAFE.ensureClassInitialized after the
>>> LDC of the class.
>>>
>>> If thats the case we could stuff a global UNSAFE instance in the
>>> constant pool when anonymously defining the class (much like direct
>>> method handles to fields).
>>
>> or to call an empty static method generated on purpose by javac.
>>
>>>
>>> Paul.
>>
>> Rémi
>>
More information about the valhalla-dev
mailing list