"Java doubts" final domain variable initialization order

Source: Internet
Author: User


The code is as follows:

public class Example049 {private final int overtime;public static final Example049 INSTANCE = new Example049 ();//1private static final int current_year = Calendar.getinstance (). get (Calendar.year);//2private Example049 () {overtime = Current_ YEAR-1970;} public int Getovertime () {return overtime;} public static void Main (string[] args) {System.out.println (Instance.getovertime ());}}

Result Description:

The output is 1970, and if 1 and 2 are swapped, the output is the difference--45 minus 1970 for the current year.

Code Analysis:

The problems encountered by the program are caused by loops in the class initialization order . The initialization of a class is triggered by the virtual machine's call to its main method. First, its static domain is set to the default value, where the INSTANCE domain is set to Null,current_year is set to 0,overtime is set to 0. Next, the static domain initializers perform the initialization in the order in which they appear. The value of the static domain instance is calculated by invoking the constructor. The constructor initializes the overtime with an expression that involves the static domain current_year. In general, reading a static domain is one of the events that causes a class to be initialized, but we are already initializing the class, and the recursive initialization attempt is ignored directly . Therefore, the value of Current_year is still its default value of 0, which is why the result is-1930. Change the position of 2 and 1, the static domain Current_year will be initialized first, and then initialize instance,Current_year already has the correct value, so the output result is correct.

The program shows that before the static domain of the final type is initialized, there is a possibility to read its value, and at this point the static domain contains only the default value of the type to which it belongs. This is contrary to intuition, because we typically treat final types of fields as constants. A field of the final type is a constant only if its initialization expression is a constant expression.

Problems caused by loops in class initialization are difficult to diagnose, but once diagnosed, they are often easily corrected. To revise a class initialization loop, you need to re-order the initializer for the static domain so that each initializer appears before any dependent initializers.

Some common design patterns are essentially initializing loops, especially the singleton pattern (Singleton) and the service provider Framework (Services Provider framework), which are presented in this case. The type-Safe enumeration pattern (Typesafe enum pattern) also causes a cycle of class initialization.

in short , be wary of class initialization loops. The simplest loops involve only a single class, but they may also involve multiple classes. Class initialization loops are not always bad, but they can cause the constructor to be called before the static domain is initialized. Static fields, even the final type of static fields, may be read out of their default values before they are initialized.


Note: This "Java doubts" series are bloggers read the original book "Java Doubts" after the original book on the explanation and examples of the adaptation and then write a blog post. All examples are personally tested and shared on GitHub. Use these examples to motivate yourself to benefit others. At the same time, all the posts in this series will be published in the blogger personal public search "Love Ape" or "ape_it" to facilitate reading. If there is any infringement of the original rights of the author, please inform the blogger in time to delete if the reader has objections to the content of the text or questions are welcome through the blog post or public messages and other ways to discuss together.

Source code Address Https://github.com/rocwinger/java-disabuse


This article from "Winger" blog, declined reprint!

"Java doubts" final domain variable initialization order

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.