|
Class initialization and object initialization are the two most important aspects of the JVM-managed type life cycle, with Google over the web, with a lot of articles about the class loading mechanism, but there are few articles on class initialization and object initialization, especially articles from bytecode and JVM hierarchies that are rarely seen.
In this paper, we mainly analyze the whole process of class and object initialization, introduce the source code into the JVM bytecode, and parse the key points of the JVM execution process through a practical problem, and put the relevant JVM specification and some internal theory knowledge of the JVM into the text. The collaboration between object initialization and class initialization, as well as possible conflict issues, is described in a combination of theory and practice.
Problem Introduction
Recently I was debugging a parser for an enumeration type that was loading 10,000 of the enumeration code in the database into the cache, in order to quickly locate the enumeration code and all of the enumeration elements of the specific enumeration class, the class takes two policies to set up the memory index while loading the enumeration code. Since this class is a public service class, it is used at every level of the program, so I implement it as a singleton class. This class works fine before I adjust the position of the class instantiation statement, but my program no longer works for me until I adjust the class instantiation statement to a static initialization statement. Here is the sample code after my simplification:
[List I]
Package com.ccb.framework.enums;
Import java.util.Collections;
Import Java.util.HashMap;
Import Java.util.Map;
public class Cachingenumresolver {
Single-state instance all problems are caused by this line
private static final Cachingenumresolver Single_enum_resolver = new Cachingenumresolver ();
/*msgcode->category Memory Index */
private static Map Code_map_cache;
static {
Code_map_cache = new HashMap ();
To illustrate the problem, I'm initializing a piece of data here
Code_map_cache.put ("0", "Beijing");
}
Private, for single instance
Private Cachingenumresolver () {
Initializing the load data causes problems, and the method also has to be responsible.
Initenums ();
}
/** * Initialize all enum types */
public static void Initenums () {
The ~~~~~~~~~ problem begins here to expose ~~~~~~~~~~~//
if (null = = Code_map_cache) {
System.out.println ("Code_map_cache is empty, the problem begins to be exposed here.");
Code_map_cache = new HashMap ();
}
Code_map_cache.put ("1", "Beijing");
Code_map_cache.put ("2", "Yunnan province");
... other code ...
}
Public Map GetCache () {
Return Collections.unmodifiablemap (Code_map_cache);
}
/** * Get a singleton instance * * @return * *
public static Cachingenumresolver getinstance () {
return single_enum_resolver;
}
public static void Main (string[] args) {
System.out.println (Cachingenumresolver.getinstance (). GetCache ());
}
} |
Presumably everyone looked at the above code will feel a bit dazed, this class does not seem to be a problem ah, this is really a typical a hungry man type of single-state mode Ah, how can there be problems?
Yes, he doesn't seem to have a problem, but if he is run, the result is that he won't work for you correctly. Run the class, and the result of the execution is:
[Listing II]
Code_map_cache is empty, the problem begins to be exposed here. {0 = Beijing}
How could my program do that? Why is Code_map_cache empty in the Initenum () method? Why I output the Code_map_cache content only one element, the other two elements????!!
See here, if you are debugging the program, you must feel very strange at the moment, is there a problem with my JVM? Not too! If not, then what's wrong with my program? This is definitely not the result I want. But in fact, no matter how to modify the Initenum () method is useless, at least I certainly do not suspect that the problem may be in the creation of Cachingenumresolver instance of the link. It's because I'm too sure of my way of creating cachingenumresolver instances, and the fact that the Java class initialization and object instantiation underlying principles are somewhat biased, which makes me pay for three or four hours-about half a day of good youth.
So where does the problem really go? Why is there such a strange thing? Before we solve this problem, let's take a look at the underlying mechanism of the JVM's class and object initialization.
Life cycle of a class
|
It shows the class life cycle flow; In this article, I'm just going to talk about the "initialization" and "Object instantiation" phases of the class.
|
Class initialization
Class initialization phase, which is the last work in the previous phase of a class or interface being used for the first time, this stage is responsible for assigning the correct initial value to the class variable.
The Java compiler collects all of the class-variable initialization statements and static initializers of the type into the <clinit> method, which can only be called by the JVM and is dedicated to the initialization work.
In addition to interfaces, before initializing a class, you must ensure that its direct superclass has been initialized, and that the initialization process is guaranteed to be thread-safe by the JVM. Also, not all classes will have a <clinit> () method, and the class will not have a <clinit> () method in the following conditions:
The class does not declare any class variables or static initialization statements, which declare class variables, but do not explicitly use class-variable initialization statements or static initialization statement initialization, which contains only class-variable initialization statements for static final variables, and class-variable initialization statements are compile-time-constant expressions.
Object initialization
When classes are loaded, concatenated, and initialized, the class is ready to be used. Object instantiation and initialization are activities that are the beginning of the object's life, where we mainly discuss the characteristics of the initialization of the object.
The Java compiler generates at least one instance initialization method for the class when compiling each class-the "<init> ()" method. This method corresponds to each constructor method in the source code, and if the class does not explicitly declare any constructor methods, the compiler generates a default parameterless constructor for that class, which simply calls the parent class's parameterless constructor, and at the same time generates a "<init" that corresponds to the default constructor method. > () "Method.
In general, the code included in the,<init> () method might be: Call another <init> () method, initialize the instance variable, and the code within its corresponding constructor method. If the constructor is explicitly started by invoking another constructor in the same class, then its corresponding <init> () method body includes a call to the <init> () method of this class, and all bytecode within the constructor method applied.
If the constructed method does not start by calling other constructors of its own class, and the object is not an object, then the <init> () method includes a call to the parent class <init> () method, and a byte code for the instance variable initialization method The last is the method body bytecode corresponding to the constructor.
If this class is Object, then its <init> () method does not include a call to the parent class <init> () method.
The initialization time of the class
So far, we have probably learned about the stages in the class life cycle, but the beginning of the life cycle of this class--when is class loading triggered? When is the class initialized? Let us continue to find the answer with these three questions.
The Java virtual Machine specification strictly defines the timing of the initialization of the class: "Initialize on first active use"--"initializing on initial active usage". This rule directly affects the mechanism of class loading, joining, and initializing classes-because it must already be connected before the type is initialized, but it must be ensured that it has already been loaded before the connection.
The Java virtual machine specification does not have a strict definition of the class loading timing related to the initialization timing, which makes it possible for the JVM to implement different loading strategies according to its own characteristics. We can think about the implementation of the Jboss AOP framework, which is in the process of loading your class file--inserting an AOP-related interception bytecode, which allows it to be completely transparent to the programmer, even if you create an object instance with the new operator can be blocked by the AOP framework Cut--The corresponding Spring AOP, you have to get the managed objects that have been represented by AOP through his beanfactory, and of course the drawbacks of JBoss AOP are obvious--he is tied to the JBoss server, and you can't easily migrate to other servers. Well ..., speaking of which is a bit off-topic here, to know that the AOP implementation strategy can write a thick book, hehe, this stop.
Having said that, the initialization time of a class is when it is "on the first active use", then, under what circumstances will it meet the requirements of the first active use?
First-time active use case:
•--new, reflection, cloning, or deserialization when creating a new instance of a class;
• When invoking a static method of a class;
• When using a static field of a class or interface or assigning a value to the field (except for the final field);
• When invoking some of the reflection methods of Java
• When initializing a subclass of a class
• The startup class that contains the main () method when the virtual machine is started.
In addition to the above scenarios, all other ways of using Java types are passive, and they do not cause initialization of classes.
Where the hell is my problem?
Well, after we understand the class initialization and object initialization mechanism of the JVM, we have a theoretical basis and can rationally analyze the problem.
Let's take a look at the bytecode from the Java source code in front of [listing one]:
[List III]
public class Com.ccb.framework.enums.CachingEnumResolver extendsjava.lang.object{
static {};
code:0: New #2;
Class Cachingenumresolver
3:dup
4:invokespecial #14;
Method "<init>":() V①
7:putstatic #16;
Field Single_enum_resolver:lcom/ccb/framework/enums/cachingenumresolver;
10:new #18;
Class Hashmap②
13:dup
14:invokespecial #19;
Method Java/util/hashmap. " <init> ":() V
17:putstatic #21;
Field Code_map_cache:ljava/util/map;
20:getstatic #21;
Field Code_map_cache:ljava/util/map;
23:LDC #23;
String 0
25:LDC #25;
String Beijing
27:invokeinterface #31, 3;
Interfacemethod java/util/map.put: (ljava/lang/object; Ljava/lang/object;) Ljava/lang/object; ③
32:pop 33:returnprivate com.ccb.framework.enums.CachingEnumResolver ();
code:0: Aload_0 1:invokespecial #34;
Method java/lang/object. " <init> ":() V 4:invokestatic #37;
Method initenums: () v④7:returnpublic static void Initenums ();
code:0: Getstatic #21;
Field Code_map_cache:ljava/util/map;
⑤3:ifnonnull 6:getstatic #44;
Field Java/lang/system.out:ljava/io/printstream;
9:LDC #46;
String Code_map_cache is empty and the problem begins to be exposed here.
11:invokevirtual #52;
Method java/io/printstream.println: (ljava/lang/string;) V 14:new #18;
Class HashMap 17:dup 18:invokespecial #19;
Method Java/util/hashmap. " <init> ":() v⑥21:putstatic #21;
Field Code_map_cache:ljava/util/map;
24:getstatic #21;
Field Code_map_cache:ljava/util/map;
27:LDC #54;
String 1 29:LDC #25;
String Beijing 31:invokeinterface #31, 3;
Interfacemethod java/util/map.put: (ljava/lang/object;
Ljava/lang/object;) Ljava/lang/object;
⑦36:pop 37:getstatic #21;
Field Code_map_cache:ljava/util/map;
40:LDC #56;
String 2 42:LDC #58;
String Yunnan Province 44:invokeinterface #31, 3;
Interfacemethod java/util/map.put: (ljava/lang/object; Ljava/lang/object;) Ljava/lang/object;
⑧49:pop 50:returnpublic Java.util.Map GetCache ();
code:0: Getstatic #21;
Field Code_map_cache:ljava/util/map;
3:invokestatic #66;
Method Java/util/collections.unmodifiablemap: (ljava/util/map;) Ljava/util/map;
6:areturnpublic static Com.ccb.framework.enums.CachingEnumResolver getinstance ();
code:0: Getstatic #16;
Field Single_enum_resolver:lcom/ccb/framework/enums/cachingenumresolver;
⑨3:areturn} |
If [listing one] above shows that the contents of the list are bytecode content in the JDK1.4 environment, this list may not be much of an attraction for most of the brothers, because these JVM instructions are really not as nice and understandable as the source code. But it's really the most straightforward way to find and locate problems, and the answer we want is in this JVM manifest.
Now let's initialize this class from class to object instance initialization for the code execution trajectory in the full process analysis [listing one].
As mentioned earlier, class initialization is the last pre-order work when the class is actually available, which is responsible for the correct initialization values for all classes, which are thread-safe and that the JVM guarantees multithreading synchronization.
1th Step: Call the class initialization method cachingenumresolver.<clinit> (), the method is not visible to the outside world, in other words, the JVM internal special Method,<clinit> () includes the All initialization statements within Cachingenumresolver that have a class variable with the specified initial value. It is important to note that not every class has the method, and the specific content is described earlier.
2nd step: In the <clinit> () method, let's look at the "①" line in the bytecode, which is combined with the above two lines to represent the new Cachingenumresolver object instance, and the line of code itself refers to the call The <init> () method of the Cachingenumresolver class. Each Java class has a <init> () method, which is generated by the Java compiler at compile time and is not visible to the outside,<init> () All statements within the method include all instance variable initialization statements with the specified initialization values and the constructor methods of the Java class. Objects are initialized by this method when they are instantiated. However, to this stage, a potential problem has been laid in the ambush, waiting for you to invade.
3rd step: Let's look down the execution order, the "④" line, where the row is the constructor of the class, which first calls the parent class's constructor <init> () initializes the parent object, and then calls Cachingenumresolver.initenum () method to load the data.
4th step: The "⑤" row, which gets the value of the "Code_map_cache" field, which is null at run time. Notice that the problem is beginning to show. (as a programmer you must be hoping that the field has been initialized and that it has not been initialized yet). By judgement, because the field is NULL, the program will continue to execute to the "⑥" line, and the fields will be instantiated as HashMap ().
5th step: In the "⑦", "⑧" line, its function is to fill in the "Code_map_cache" field two data.
6th step: Exit the Object Initialization method <init> () to initialize the generated object instance to the class field "Single_enum_resolver". (Note that the class variable in the object instance is not initialized at this point, and the class variable "Code_map_cache" that was assigned by <init> () is called by the Initenum () method, which is the <clinit> () method and the field is not initialized. It will also be overwritten again later in the class initialization process).
7th step: Continue execution of the successor code within the <clinit> () method, the "②" line, which instantiates the "Code_map_cache" field as an HashMap instance (note: The field has been assigned a value on the object instantiation and is now re-assigned to another instance, at this moment , the value of the class variable for the instance referenced by the "Code_map_cache" variable is overwritten, and our question already has an answer.
The 8th step: the initialization of the class is complete, and the instantiation of the Singleton class is completed.
By performing a process analysis of the above bytecode, perhaps you have clearly understood the underlying cause of the error, or perhaps you have already been confused by the above analysis process, but also did not fold, although I can also from the source code point of view to explain the problem, but this is not enough depth, but also for personal views, Lack of credibility.
How to Solve
To solve the problem of the above code is simple, that is, the "single_enum_resolver" variable initialization assignment statement to the getinstance () method can be. In other words, avoid instantiating the class from the inside when the class is not initialized or referencing a field that has not been initialized during initialization.
Written in the last
Quiet down the dry heart, carefully consider whether you really mastered the topic of this article, if you feel that you have complete or basic grasp, then very good, in the end, I will be the previous code to do a little change, please think about the following two sets of programs are also problematic?
Program One
public class Cachingenumresolver {
public static Map Code_map_cache;
static {
Code_map_cache = new HashMap ();
To illustrate the problem, I'm initializing a piece of data here
Code_map_cache.put ("0", "Beijing");
Initenums ();
} |
Program Two
public class Cachingenumresolver {
private static final Cachingenumresolver single_enum_resolver;
public static Map Code_map_cache;
static {
Code_map_cache = new HashMap ();
To illustrate the problem, I'm initializing a piece of data here
Code_map_cache.put ("0", "Beijing");
Single_enum_resolver = new Cachingenumresolver ();
Initenums ();
} |
Finally, a little bit of a speech about the JAVA community: Nowadays it is a time when various open source frameworks are in vogue, and Spring is a great way to attract the attention of a large number of JEE developers (I am also a member of the fans). However, let's take a closer look at the spring community, for example, how many spring fans have studied spring source code? How many people have a real deep understanding of Spring design ideas? Of course, I am not qualified to say things in such a tone, I just want to show a point of view-learning things must be "radical reform".
|