In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is mainly about "how many bytes does new Object () occupy in java?" interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how many bytes does new Object () occupy in java?"
Preface
The Java virtual machine stack is thread-private and has no data security issues, while the heap is more complex than the Java virtual machine stack.
Because the heap is a piece of memory space shared by all threads, there will be thread safety problems, and garbage collection is mainly the collection of space in the heap.
So it is necessary for us to have an in-depth understanding of the layout of the heap. Now let's continue to analyze the in-heap layout and the layout of Java objects in memory.
The direction of the object
Let's take a look at a piece of code:
Package com.zwx.jvm
Public class HeapMemory {
Private Object obj1 = new Object ()
Public static void main (String [] args) {
Object obj2 = new Object ()
}
}
In the above code, what's the difference between obj1 and obj2 in memory?
The method area stores the structure of each class, such as runtime constant pools, property and method data, and data such as methods and constructors.
So our obj1 has a method area, and new creates an object instance, which is stored in the heap, so we have the following diagram (the method area points to the heap):
Insert a picture description here
Obj2 is a local variable in the method, which is stored in the local variable table in the stack frame of the Java virtual machine stack. This is the classical stack pointing heap:
Insert a picture description here
Let's think again. One of our variables points to the heap, and only an instance object is stored in the heap, so how do the sample objects in the heap know which Class they belong to?
In other words, how does this example know its corresponding class meta-information? This involves how a Java object is laid out in memory.
Java memory model
Object memory can be divided into three areas:
Object head (Header)
Instance data (Instance Data)
Align fill (Padding)
Taking a 64-bit operating system as an example (when pointer compression is not enabled), the layout of the Java object is shown below:
Insert a picture description here
The alignment padding in the image above is not necessary, and if the object header and instance data add up to a multiple of 8 bytes, then there is no need for alignment padding.
Now that we know the Java memory layout, let's look at an interview question.
Object obj=new Object () occupies bytes
This is a problem that many people will mention on the Internet, so combined with the Java memory layout above, let's take a 64-bit operating system as an example, the size of new Object () is divided into two situations:
Pointer compression is not turned on
Occupancy size: 8 (Mark Word) + 8 (Class Pointer) = 16 bytes
Pointer compression is on (default is on)
When pointer compression is turned on, the Class Pointer is compressed to 4 bytes, and the final size is:
8 (Mark Word) + 4 (Class Pointer) + 4 (alignment padding) = 16 bytes
Is this the result or not? Let's check it out.
First introduce a pom dependency:
Org.openjdk.jol
Jol-core
0.10
Then create a simple demo:
Package com.zwx.jvm
Import org.openjdk.jol.info.ClassLayout
Public class HeapMemory {
Public static void main (String [] args) {
Object obj = new Object ()
System.out.println (ClassLayout.parseInstance (obj). ToPrintable ()
}
}
The output is as follows:
Insert a picture description here
The final result is 16 bytes, no problem, this is because pointer compression is turned on by default, so let's turn pointer compression off and try again.
-XX:+UseCompressedOops enables pointer compression
-XX:-UseCompressedOops turns off pointer compression
Insert a picture description here
Run it again and get the following results:
Insert a picture description here
As you can see, there is no alignment padding at this time, but the occupied size is still 16 bits.
Let's demonstrate the size of an object with attributes.
Create a new class with only one byte attribute inside:
Package com.zwx.jvm
Public class MyItem {
Byte I = 0
}
Then output the size of this class in the scenarios where pointer compression is on and off, respectively.
Package com.zwx.jvm
Import org.openjdk.jol.info.ClassLayout
Public class HeapMemory {
Public static void main (String [] args) {
MyItem myItem = new MyItem ()
System.out.println (ClassLayout.parseInstance (myItem). ToPrintable ()
}
}
Enable pointer compression, which takes up 16 bytes:
Insert a picture description here
Turn off pointer compression, which takes up 24 bytes:
Insert a picture description here
At this time, you can see the advantage of turning on pointer compression, if you continue to create a large number of objects, pointer compression is still optimized for performance.
Access to objects
After creating an object, of course we need to access it, so when we need to access an object, how do we navigate to it?
At present, there are two most mainstream ways to access objects:
Handle access
Direct pointer access.
Handle access
Using handle access, the Java virtual machine divides a piece of memory in the heap to store the handle pool, then the handle address is stored in the object, and then the object instance data and object type data address are stored in the handle pool.
Insert a picture here to describe direct pointer access (the method used by the Hot Spot virtual machine)
If the pointer is accessed directly, the object type data is stored directly in the object.
Insert picture description handle access and direct pointer access here to compare
In the figure above, it is easy to compare, that is, if you use handle access, there will be one more pointer positioning.
But it also has the advantage that if an object is moved (the address has been changed), you only need to change the direction of the handle pool, not the point within the reference object.
If you use direct pointer access, you also need to modify the reference point in the local variable table.
Heap memory
As we mentioned above, the Mark Word in the Java object header stores the generational age of the object, so what is the generational age?
The generation age of an object can be understood as the number of garbage collection. When an object still exists after a garbage collection, the generation age will be increased by 1.
In 64-bit virtual machines, the generation age accounts for 4 places, with a maximum value of 15. The generation age defaults to 0000, which increases gradually with the number of garbage collection.
According to the age of generations, the Java heap memory is divided into Young area and Old area, and the object allocation will go to Young area first.
If you reach a certain generational age (- XX:MaxTenuringThreshold can be set in size, the default is 15), you will enter the Old area (note: if an object is too large, it will enter the Old area directly).
The reason for this division is that if there is only one zone in the whole heap, all objects in the heap need to be scanned every time during garbage collection, which is a waste of performance.
In fact, the life cycle of most Java objects is very short, once an object can not be recycled many times, it can be considered that it may not be recycled in the next garbage collection.
Therefore, garbage collection in Young area and Old area can be carried out separately. Only when there is no space available in Young area after garbage collection, then trigger garbage collection in Old area.
Insert the picture description Young area here
Now that the Young area is split, let's take a look at the following scenario. The following Young is an overview of garbage collection:
Insert a picture description here
If you now have an object that takes up the size of two objects, you will find that you can't put it down, and then GC (garbage collection) will be triggered.
But once GC (garbage collection) is triggered, it has an impact on the user thread, because all user threads need to be stopped during the GC process to ensure that the object reference does not constantly change.
Sun calls this event: Stop the World (STW).
So generally speaking, the less GC, the better, but in fact, you can see that at least 3 objects can be put in the image above, as long as the objects are placed in order, then they can be put down.
So this gives rise to a problem, obviously there is space, but because the space is discontinuous, the object fails to apply for memory, resulting in triggering GC, so how to solve this problem?
The solution is to put the objects in the Young area in order, so there is a method to divide the Young area into two areas: the Eden area and the Survivor area.
Insert a picture description here
The specific operation is as follows: after an object comes, it is first assigned to the Eden area, and when the Eden area is full, the GC is triggered.
After GC, in order to prevent spatial discontinuity, the surviving objects are copied to the Survivor area, and then the Eden area can be completely cleaned up.
Of course, there is a premise that most objects have a very short life cycle, and most of the objects in the Eden area can be recycled in a basic garbage collection (this premise has been summed up after testing).
When GC is triggered, the Survivor area will also be recycled, not just the Eden area alone.
But this problem comes again, the Eden region ensures that the space is basically continuous, but the Survivor region may produce space debris, resulting in discontinuity.
So the Survivor area was split in two again.
Insert a picture description here
At this point, the workflow becomes like this again:
First, the space is allocated in the Eden area. After the GC,GC is triggered when the Eden area is full, the surviving objects are copied to the S0 area (S1 area is empty), and then continue to allocate objects in the Eden area.
After triggering GC again, if you find that there is no room in S0 area (space debris is actually still available), then copy the S0 area object to S1 area, and copy the surviving object to S1 area, then S0 area is empty and operate repeatedly in turn.
If it is said that the space object in S0 area or S1 area can not be put down after copying and moving, it means that it is really full at this time, then go to the elderly area to borrow some space (this is the guarantee mechanism, the old age needs to provide this kind of space allocation guarantee).
If there is not enough space in the old age area, then Full GC will be triggered, and if it is not enough, an OutOfMemeoyError exception will be thrown.
Note: in order to ensure that each replication between S0 and S1 can proceed smoothly, the size of S0 and S1 must be the same, and one area must be empty at the same time.
Although this practice will lead to a small waste of space, but in terms of other performance improvements, it is worth it.
Old area
When the object in the Young area reaches the set generation age, the object will enter the Old area, and the Full GC will be triggered when the Old area is full. If the space still cannot be cleared, an OutOfMemeoyError exception will be thrown.
Noun literacy
There are a lot of new nouns mentioned above, but in fact, many of these nouns have other names, but I still think it is necessary to know about this.
Garbage collection: GC for short.
Minor GC: GC for the new generation
Major GC: for the old GC, generally speaking, when the old age triggers GC, it also triggers Minor GC, which is equivalent to triggering Full GC.
Full GC: GC occurred at the same time in the Cenozoic era and the old age.
Young area: Cenozoic era
Old District: the Old Age
Eden area: no Chinese translation is found yet (Garden of Eden?)
Surcivor area: survival area
S0 and S1: also known as from area and to area. Note that the identities of from and to are constantly exchanged, and S0 and S1 must be equal, and ensure that an area is empty.
The life trajectory map of an object
From the above introduction, you should have a general impression that an object will continue to flow in Eden, S0, S1, and Old (except for short-lived objects that will be recycled in the first place, of course).
We can get the following flowchart:
At this point, I believe you have a deeper understanding of "how many bytes are occupied by new Object () in java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.