In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "the process of creating Java objects". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Class initializes the trigger action for the creation of the class
In Java code, there are many behaviors that can cause object creation, one of the most intuitive is to use the new keyword to call the constructor of a class to explicitly create an object, which is called in the Java specification: object creation caused by executing an expression for class instance creation. In addition, we can create objects using reflection mechanisms (newInstance method of the Class class, newInstance method of the Constructor class), Clone method, deserialization, and so on.
Create an object using the new keyword
This is our most common and simplest way to create an object, in which we can call any constructor (no parameter and parameter) to create the object. For example:
Student student = new Student (); use the newInstance method of the Class class (reflection mechanism)
We can also use the newInstance method of the Class class to create an object through the reflection mechanism of Java. In fact, this newInstance method calls a no-parameter constructor to create an object, such as:
Student student2 = (Student) Class.forName ("Student class fully qualified name"). NewInstance (); Student stu = Student.class.newInstance (); use the newInstance method of the Constructor class (reflection mechanism)
There is also a newInstance method in the java.lang.relect.Constructor class that can create objects, which is similar to the newInstance method in the Class class, but the newInstance method of the Constructor class is more powerful. We can use this newInstance method to call parameterized and private constructors, such as:
Public class Student {private int id; public Student (Integer id) {this.id = id;} public static void main (String [] args) throws Exception {Constructor constructor = Student.class .getConstructor (Integer.class); Student stu3 = constructor.newInstance (123);}
These two ways of creating objects using the newInstance method use the reflection mechanism of Java. In fact, the newInstance method of Class also calls the newInstance method of Constructor.
Create an object using the Clone method
Whenever we call an object's clone method, JVM will help us create a new, identical object. In particular, no constructor will be called during object creation with the clone method. To put it simply, to use the clone method, we must first implement the Cloneable interface and its defined clone method, which is also the application of the prototype pattern. For example:
Public class Student implements Cloneable {private int id; public Student (Integer id) {this.id = id;} @ Override protected Object clone () throws CloneNotSupportedException {/ / TODO Auto-generated method stub return super.clone ();} public static void main (String [] args) throws Exception {Constructor constructor = Student.class .getConstructor (Integer.class); Student stu3 = constructor.newInstance Student stu4 = (Student) stu3.clone ();}} create objects using the (deserialization) mechanism
When we deserialize an object, JVM creates a separate object for us, and JVM does not call any constructors in the process. To deserialize an object, we need to have our class implement the Serializable interface, such as:
Public class Student implements Cloneable, Serializable {private int id; public Student (Integer id) {this.id = id;} @ Override public String toString () {return "Student [id=" + id + "]";} public static void main (String [] args) throws Exception {Constructor constructor = Student.class .getConstructor (Integer.class); Student stu3 = constructor.newInstance (123) / / write object ObjectOutputStream output = new ObjectOutputStream (new FileOutputStream ("student.bin")); output.writeObject (stu3); output.close (); / / read object ObjectInputStream input = new ObjectInputStream (new FileInputStream ("student.bin")); Student stu5 = (Student) input.readObject (); System.out.println (stu5) }} create objects using the Unsafe class
The Unsafe class gives Java the ability to manipulate memory space like pointers in C, but it also brings pointer problems. Excessive use of the Unsafe class increases the chance of error, so it is not officially recommended by Java, and there is little official documentation. Oracle is planning to remove the Unsafe class from Java 9, and if so, the impact would be too big.
We cannot create Unsafe objects directly. Here we use the reflection method to get
Private static Unsafe getUnsafe () {try {Field field = Unsafe.class.getDeclaredField ("theUnsafe"); field.setAccessible (true); Unsafe unsafe = (Unsafe) field.get (null); return unsafe;} catch (Exception e) {e.printStackTrace ();} return null;}
After you get the object, call the native method allocateInstance to create an object instance
Object event = unsafe.allocateInstance (Test.class)
From the Java virtual machine level, except for the way to create objects ((invokespecial)) using the new keyword, all other ways are directly created by transforming into invokevirtual instructions.
Introduction to the concept of initialization and instantiation of class
The process of creating Java objects often includes two stages: class initialization and class instantiation. The initialization of the class comes before the instantiation of the class.
Note: this is just the opposite of spring's bean. The life cycle of spring's bean is mainly instantiating the java object first, then operating the properties, and finally initializing. Here initialization is not the initialization of the java object, but the initialization of the parameters of the spring (initMethod, afterPropertiesSet), and so on. @ PostConstruct is the pre-intercept initialization method.
The main responsibilities for initializing the class are:
Class constructor call () to initialize relevant static code blocks and static variable assignments
The object must be properly initialized before it can be used, which is specified by the Java specification. When instantiating an object, JVM first checks to see if the relevant type has been loaded and initialized, and if not, JVM loads immediately and calls the class constructor to complete class initialization.
Note: you can see that the initialization of the class is mainly up to the point in time when the class constructor variable ends execution.
Instantiation of class
Main responsibilities: instance constructor invocation (), memory allocation, property assignment mechanism worthy of customization.
The meaning of class instantiation itself is the concept of object, in fact, it is the process of instantiating the corresponding object.
Memory allocation of instance objects, default initialization of instance object parameters and instantiation of instance object parameters (that is, implementation calls according to development requirements, such as calling constructors, etc.)
At this point, it is generally in the stage before use after the initialization of the loading phase is completed, and the next step is to instantiate the class.
During or after the initialization of the class, the class will be instantiated according to the specific situation. First, there are the following steps:
The java virtual machine allocates memory to store itself and its instance variables inherited from the parent class.
While allocating memory for these instance variables, these instance variables are first assigned default values (zero values) [this zero value is similar to the preparation in the load phase by assigning semantic-level default values first, rather than the actual initialization of the parameter]
After the memory allocation is completed, the method is called, and the Java virtual machine executes the construction code block, construction method, method parameter execution, and so on. Will assign the value given by our program to the newly created object
Summary: creating an object involves the following two procedures:
The class constructor completes class initialization (assigns static variable default values)
Class instantiation (allocates memory, assigns default values, performs custom assignment operations)
The class instantiation process detects whether the class is loaded
When the Java virtual machine encounters a new instruction, it will first check whether the parameters of the instruction can locate a symbolic reference to a class in the constant pool, and check whether the class represented by the symbolic reference has been loaded, parsed, and initialized. If not, you must first perform the corresponding class loading process * *.
Allocate memory for new objects
After the class is loaded and the class initialization is completed, the virtual machine then allocates memory for the new object. The amount of memory required by the object can be fully determined after the class is loaded and initialized.
Determine the object memory size
The size of the object is determined after the class is loaded, and the object can be divided into three pieces in memory.
Object head
Size determination is class independent and operating system dependent, including tag fields and type pointers
Instance data
Even if the instance fields of the parent class are overwritten or decorated by the subclass, the memory is still allocated to it, and the fields of the same width are assigned together. Second, the fields of the parent class are assigned and initialized before the subclass.
Align fill
Meet the requirements of the virtual machine for multiples of 8
Object to allocate memory.
Assuming that the memory in the Java heap is absolutely regular, with all used memory on one side and free memory on the other side, with a pointer in the middle as an indicator of the demarcation point, then allocating memory is simply moving that pointer to the free space by a distance equal to the size of the object, which is called "pointer collision".
If the memory in the Java heap is not regular, and the used memory and free memory are interlaced, there is no way to simply collide with each other. The virtual machine must maintain a list, record which blocks of memory are available, find a large enough space from the list to allocate to the object instance, and update the records on the list. This allocation method is called "free list".
The choice of allocation method is determined by whether the Java heap is neat or not, and whether the Java heap is neat or not is determined by whether the garbage collector used has the compression function.
Object creation is a very frequent behavior during the execution of the virtual machine, only modifying the location pointed to by a pointer is not thread-safe in the case of concurrency. So there are also two solutions:
Use CAS with a failed retry to ensure the atomicity of the update operation.
(TLAB) each thread is pre-allocated a thread private allocation buffer in the Java heap, and which thread needs to allocate memory as long as it is allocated in the thread private allocation buffer.
Initialize zero
Initialize the allocated memory space to zero, which ensures that the instance field is not assigned a value and can be used directly. If TLAB is used, this step can be done in advance to the time of TLAB allocation.
After the memory allocation is completed, the virtual machine needs to initialize the allocated memory space to zero (excluding object headers). This step ensures that the instance fields of the object can be used directly without initial values in the Java code, and the program can access the zero values corresponding to the data types of these fields.
Make the necessary object header settings
The virtual machine needs to set the necessary information on the object, such as which class the object is, how to find the metadata information of the class, the hash code of the object, the GC generation age of the object and so on. This information is stored in the object header of the object, which is mainly responsible for 5 points.
Object is an instance of which class
How to find the metadata information for a class
Hash code of the object
GC generation age information of the object
Identification of locks, etc.
After performing the above steps, an object has been generated from a virtual machine point of view, but for the java program, the constructor has not yet started to execute. Next, initialize the object according to the requirements of the constructor.
The object header mainly contains two types of information. The first category is used to store the runtime data of the object itself, such as hash code, GC generation age, lock status flag, lock held by thread, biased thread ID, biased timestamp and so on. The other part of the object header is the type pointer, which is the pointer of the object to its type metadata.
The type data part is the valid information really stored by the object, that is, the various types of field content defined in the program code.
Aligned padding: the size of any object must be an integral multiple of 8 bytes.
Access location of object
With handle access, a piece of memory may be allocated in the Java heap to serve as a handle pool. In the Reference variable is the address of the handle pool, which holds pointers to object instance data and pointers to object type data.
With direct access, the reference variable stores the instance data of the object, and the instance data of the object contains pointers to the data of the object type.
Execute the init method
After all the above work is done, a new object has been created from the perspective of the virtual machine, but from the perspective of the Java program, the object creation has just begun, the method has not been executed, and all fields are still zero. So generally speaking, the execution of the new instruction is followed by the execution of the method, initializing the object according to the program, so that a really available object is fully generated.
Summarize the process of creating an object
To detect whether the class is loaded or not, first load → to allocate memory for new objects → initializes the allocated memory space to zero → * * make the necessary settings for the object (object header) * * the → execution method initializes the object
Expand and extend
There are five cases in which class initialization is required (there are and only these five).
When the four new getstatic putstatic invokestatic instructions are encountered, if the class is not initialized, it will trigger the initialization of the class.
The most common situation corresponding to the four instructions is to instantiate the object using the new keyword, read static variables, set static variables (except where the compile-time results are put into the constant pool, which will trigger the previous stages), and call the static methods of the class.
Use the method of the java.lang.reflect package to make a reflection call to the class
Initialize a parent class when initializing a class if the parent class is not initialized
Common references that do not trigger initialization
Referencing the static variable of the parent class through the subclass initializes the parent class, not the subclass.
Create an array of classes
Reference variables in the constant pool
Load
Get the binary stream of the class by name and generate the class object in memory.
Verification
Verifying the correctness and security of binary streams includes four steps: file format verification, metadata verification, bytecode verification and symbol reference verification.
Prepare for
Allocate space to the class variable (static) and complete initialization Note: if it is not a final variable, the value is zero.
Analysis
Resolve symbolic references to direct references, including class or interface parsing, field parsing, class method parsing, interface method parsing.
Initialization
Executes the () method of the class, which consists of all assignment operations to static variables and all static code blocks. The virtual machine ensures that the () method of the parent class ends before the method of the subclass starts, and provides thread safety guarantee (similar to double check, when multiple threads initialize at the same time, only one thread enters the method, other threads block, and other threads do not enter the method after execution is completed).
Class loader-parent delegation model
According to the implementation model of classloader recommended by Java, all classloaders except the startup classloader (bootstrap classLoader) should have a parent loader. This relationship is not achieved by inheritance, but by composition. When the class loader receives the load request, it first requests the parent loader to load, and if the parent loader cannot load, it calls its own load method.
Follow the parent delegation model: override the findClass () method if we want to customize the classloader.
Do not want to follow the parental delegation type: the solution is to override the loadClass () method
Class Loader-Classification
According to the parental appointment, it can be divided into four categories from top to bottom.
Start the class loader (Bootstrap classLoader) to load the class with the specified file name under\ lib
The extended class loader (Extension classLoader) loads classes under\ lib\ ext
System class loader (application class loader) loads classes in Classpath
Custom class loader
Common class loaders that do not follow parental delegation:
SPI (Service Provider Interface) Loader-Thread context Loader implements the parent loader to request a load from the child loader
OSGi modular loader each module has a loading process of a custom classloader mesh structure
Allocate memory
Memory allocation is closely related to memory recovery, and there are different allocation strategies according to different recovery strategies.
If you are using a garbage collection strategy with a compression process, such as Serial,ParNew, the memory in the Java heap is regular, and we only need to move the memory pointer back to the location of the memory size, which is called pointer collision (Bump the Pointer). If you use a recycling strategy that does not have a compression process, such as CMS, the virtual machine needs to maintain a list of which memory is available, which is called a free list (Free List)
Secondly, object creation also needs to consider the problem of thread safety. One method is to use CAS+ failure retry method to ensure thread safety, and the other is to allocate a piece of memory for each thread in advance, which is called local thread allocation buffer (Thread Local Allocation Buffer, TLAB). When creating objects, threads give priority to allocation on their own TLAB.
Object head
Object headers include
MarkWord 32bit/64bit depends on the operating system
A pointer to class metadata.
Array length if it is an array
We mainly introduce MarkWord
Depending on the lock state, markword reuses its own space to record some different information.
We notice that the age of the generation is covered when the lightweight and heavyweight lock states are overwritten, so how do we recover when the lock state is released?
The answer is that when locked, a backup of the original markword will be saved in the locked data.
That's all for the process of creating Java objects. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.