Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a Java object

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to create Java objects". In daily operations, I believe many people have doubts about how to create Java objects. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to create Java objects". Next, please follow the editor to study!

I. the way to create an object

Use the new keyword

This is the most general and general way to create an object, and it is also the easiest way. By using this method, we can call any constructor to be called (no parameter constructor is used by default)

Person p = new Person ()

Using newInstance () of the Class class, you can only call the constructor of an empty parameter, and the permission must be public

/ / get class object Class aClass = Class.forName ("priv.starfish.Person"); Person p1 = (Person) aClass.newInstance ()

Constructor's newInstance (xxx), which does not require constructors

Class aClass = Class.forName ("priv.starfish.Person"); / / get constructor Constructor constructor = aClass.getConstructor (); Person p2 = (Person) constructor.newInstance ()

Clone ()

Deep copy, you need to implement the Cloneable interface and clone () without calling any constructor

Person p3 = (Person) p.clone ()

Deserialization

Get the binary stream of an object from a file or network through serialization and deserialization techniques.

Whenever we serialize and deserialize an object, JVM creates a separate object for us. In deserialization, JVM does not use any constructors to create objects. (serialized objects need to implement Serializable)

/ / prepare a file to store the object's information File f = new File ("person.obj"); FileOutputStream fos = new FileOutputStream (f); ObjectOutputStream oos = new ObjectOutputStream (fos); / / serialize the object and write it to disk oos.writeObject (p); / / deserialize FileInputStream fis = new FileInputStream (f); ObjectInputStream ois = new ObjectInputStream (fis); / / deserialize object Person p4 = (Person) ois.readObject ()

Third-party library Objenesls

Java already supports dynamic instantiation of the Java class through Class.newInstance (), but this requires the Java class to have an appropriate constructor. Many times a Java class cannot be created in this way, for example, the constructor requires parameters, the constructor has side effects, and the constructor throws an exception. Objenesis can bypass the above restrictions

II. Steps to create an object

We are only talking about normal Java objects, excluding arrays and Class objects (the creation instructions for normal objects and array objects are different. Instructions for creating class instances: new, instructions for creating arrays: newarray,anewarray,multianewarray)

1. New instruction

When the virtual machine encounters a new instruction, it first checks whether the parameters of this instruction can locate a symbolic reference of a class in the constant pool of Metaspace, and checks whether the class represented by this symbolic reference has been loaded, parsed and initialized (that is, to determine whether the class meta-information exists). If not, the corresponding class loading process must be performed first in parent delegation mode.

two。 Allocate memory

Next, the virtual machine allocates memory for the new generation of objects. The amount of memory required by the object can be fully determined after the class is loaded. If the instance member variable is a reference variable, only the reference variable space can be allocated, that is, 4 bytes. There are two ways of allocation: "pointer collision (Bump the Pointer)" and "free list (Free List)", which is determined by whether the garbage collector is compressed or not.

If the memory is regular, pointer collisions are used to allocate memory to the object. It means that all used memory is on one side, free memory on the other, and a pointer is placed in the middle as an indicator of the demarcation point. Allocating memory is simply moving the pointer to the idle side by a distance equal to the size of the object. This method is used if the garbage collector is based on compression algorithms such as Serial and ParNew. (generally use garbage collectors with collation function, all use pointer collisions)

If the memory is irregular, the virtual machine needs to maintain a list that records which memory is available, and finds a large enough space from the list to allocate memory to the object instance when allocating memory for the object. and update the contents of the list, this allocation is called "free list". When using CMS, a collector based on the Mark-Sweep algorithm, the free list is usually used.

We all know that heap memory is shared by threads, so there will be concurrency security problems when allocating memory. How does JVM solve it?

There are generally two solutions:

Synchronize the action of allocating memory space, adopt CAS mechanism, cooperate with failed retry to ensure the atomicity of update operation.

When each thread pre-allocates a small piece of memory in the Java heap and then allocates memory to the object, it allocates directly in its own "private" memory, and when this part of the area is used up, it allocates new "private" memory. This scheme is called TLAB (Thread Local Allocation Buffer), and this part of the Buffer is split from the heap, but is exclusive to local threads.

It is worth noting that we say that TLAB is exclusive to threads, only in the "allocation" action is thread exclusive, as in reading, garbage collection and other actions are shared by threads. And there is no difference in use. In addition, TLAB only works on the new generation of Eden Space, and objects are first placed in this area when they are created, but the new generation of large objects that cannot allocate memory will go straight into the old age. Therefore, when writing Java programs, it is usually more efficient to allocate multiple small objects than large objects.

You can choose whether the virtual machine uses TLAB, which can be specified by setting the-XX:+/-UseTLAB parameter. JDK8 is enabled by default.

3. Initialization

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. For example: byte, short, long are converted into objects with the initial value of 0 and the initial value of false Boolean.

4. The initial setting of the object (sets the object header of the object)

Next, 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's Object Header. Depending on the current running state of the virtual machine, such as whether to enable bias locks, the object header will be set in different ways.

5. Method initialization

After all the above work is done, from a virtual machine point of view, a new object has been generated, but from a Java program point of view, object creation has just begun, methods have not yet been executed, and all fields are still zero. Initialize member variables, execute instantiated code blocks, call class constructors, and assign the address of objects in the heap to reference variables.

So, generally speaking, the execution of the new instruction is followed by the execution of the init method, initializing the object according to the wishes of the programmer (which should be assigning the parameters in the constructor to the object's field), so that a really available object is fully generated.

Third, the memory layout of objects

In the HotSpot virtual machine, the layout of objects stored in memory can be divided into three areas: object header (Header), instance data (Instance Data), and Padding.

Object head

The object header of the HotSpot virtual machine contains two parts of information.

The first part is used to store the runtime data of the object itself, such as hash code (HashCode), GC generation age, lock status flag, lock held by thread, biased thread ID, biased timestamp and so on.

Another part of the type pointer to the object, that is, the pointer to its class metadata, through which the virtual machine determines which class the object is (not all virtual machine implementations must retain the type pointer on the object data, that is, finding the object's metadata information does not have to pass through the object itself).

If the object is a Java array, there must also be a piece of data in the object header to record the length of the array.

Metadata: data that describes the data. Description of data and information resources. In Java, metadata is mostly represented as annotations.

Instance data

The instance data part is not only the valid information really stored by the object, but also the various types of field content defined in the program code, whether inherited from the parent class or defined in the subclass, need to be recorded. The storage order of this part is affected by the default allocation policy parameters of the virtual machine and the order of fields defined in the Java source code (fields of the same width are always assigned together).

Rules:

Fields of the same width are always assigned together

Variables defined in the parent class appear before the child class

If the CompactFields parameter is true (the default true), the narrow variable of the subclass may be inserted into the gap of the parent variable

Align fill

The alignment fill part is not inevitable, nor does it have any special meaning, it only acts as a placeholder. Because HotSpot VM's automatic memory management system requires that the starting address of an object must be an integral multiple of 8 bytes, that is, the size of an object must be an integral multiple of 8 bytes. The header part of the object is exactly a multiple of 8 bytes (1 or 2 times), so when the object instance data part is not aligned, it needs to be filled by alignment padding.

Let's deepen our understanding through a simple example.

Public class PersonObject {public static void main (String [] args) {Person person = new Person ();}} public class Person {int id = 1008; String name; Department department; {name = "anonymous user"; / / name assigned to string constant}} public class Department {int id; String name;}

IV. Access and positioning of objects

We must have created an object to use it, so how does JVM access its memory object instance through the object reference in the stack frame?

Since the reference type only specifies a reference to the object in the Java virtual machine specification, and does not define how the reference should be located and the specific location of the object in the Java heap, the object access methods implemented by different virtual machines will be different, and there are two mainstream access methods:

Handle access

If handle access is used, a piece of memory is allocated in the Java heap to serve as the handle pool. What is stored in reference is the handle address of the object, and the handle contains the specific address information of the object instance data and type data respectively. The biggest advantage of using the handle method is that the stable handle address is stored in reference, and only the instance data pointer in the handle will be changed when the object is moved (it is very common behavior to move the object during garbage collection), while the reference itself does not need to be modified.

Direct pointer (used by Hotspot)

If you use this approach, the layout of the Java heap object must consider how to place information about the access type data, and the object address is directly stored in the reference. The biggest advantage of using direct pointer is that it is faster, which saves the time cost of pointer positioning.

At this point, the study on "how to create Java objects" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report