Java: 依赖字段初始化顺序有什么风险吗?

Java: is there any risk to depend on field initializing sequence?

我正在使用像这样的 class 字段的默认初始化。我想字段将按如下顺序初始化:

class NormalInit {
    int i = 3;
    LocalDate h = LocalDate.now();
    public int year = h.getYear(); // is it safe?
}

我的问题:

(1) 我对序列的假设是否正确(这由 java 或 jvm 规范保证)?

(2)这种初始化方式有什么共同点failure/pitfall吗?

应该没问题。根据 java 内存模型和语言规范语句在单个线程中从上到下求值。

初始化块的顺序https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4

4.Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception

这个link是为了happens-before的解释:https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

技术上分配给 ih 可以重新排序,但在您的情况下,它不会对程序的语义产生任何影响。

h 取决于 year,JVM 不会重新排序这些分配。

但是i没有依赖,所以JVM可以在构造的任何时候把它初始化。