简体   繁体   中英

Compiler optimization of public static final and OSGi

I have an OSGi bundle b1 exporting a class with

public static final String MYVAL = "a"; //version 1

and a second bundle b2 is compiled and deployed using version 1 of b1.

Later on I change the value in b1 to

public static final String MYVAL = "b"; //version 2

but I only recompile and deploy b1, b2 is unchanged and not recompiled.

Is it possible that the b2 still sees value a at runtime?

The value of a referenced static final primitive or string is directly inlined into the using class. So unrelated to OSGI and any visibility rules, b2 will still contain an embedded MYVAL value of "a".

I think this is documented in the Java Language Specification, Section 13.4 :

If a field is a constant variable (§4.12.4), then deleting the keyword final or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for the usage of the field unless they are recompiled . This is true even if the usage itself is not a compile-time constant expression (§15.28).

This answer to a similar question shows a workaround. Changing the declaration so it is no longer a constant expression disables this inlining behaviour.

public static final String MYVAL = String.valueOf("a");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM