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

Case Analysis of Java object size

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article Xiaobian for you to introduce in detail the "Java object size instance analysis", the content is detailed, the steps are clear, the details are handled properly, I hope this "Java object size instance analysis" article can help you solve your doubts, following the editor's ideas slowly in depth, let's learn new knowledge.

Java raw data type

The size of the Java Primitives is well known and is available from the box

Minimum memory words for 32-bit and 64-bit systems

The minimum sizes of 32-bit and 64-bit memory words are 8 and 16 bytes, respectively. Any smaller length is rounded to 8. In the process of calculation, we will consider these two cases.

Due to the nature of the memory (byte size) structure, any memory is a multiple of 8, and additional bytes are automatically added if not for the system (but the minimum size of the 32 + 64 system is still 8 and 16 bytes).

Java object

There are no fields inside the Java object, and according to the specification, it only has metadata called header. Header consists of two parts: marker (Mark Word) and class pointer (class pointer).

Function usage size 32-bit operating system size 64-bit token word lock (synchronization), garbage collector information, hash code (from local call) 4-byte 8-byte class pointer block pointer, array length (if the object is an array) 4 bytes 4 bytes all

8 byte (0 byte offset) 16 byte (4 byte offset) Java original wrapper

In Java, everything is an object except primitives and references (the last one is hidden). So all the wrapper classes just wrap the corresponding primitive types. So wrapper size generally = object header object + internal original field size + memory gap. The sizes of all the original wrappers are shown in the table below:

Type internal original size title 32-bit total size 64-bit total size 32-bit total size 64-bit total size 32-bit total size 32-bit total size 64-bit Byte18129131616Boolean18129131616Int481212161616Float481212161616Short281210141616Char281210141616Long881216201624Double881216201624Java array

Java arrays are very similar objects-they also have different primitive and object values. The array contains the headers, the length of the array, and its cells (to primitives) or references to its cells (for objects). For your convenience, we draw an array of raw integers and large integers (wrappers).

An array of primitives (integers in our case) an array of objects (a bit integer in our case)

Therefore, you can see the main difference between the original array and the object array-the additional layer with references. In this example, most of the memory loss is due to the use of an integer wrapper, which adds 12 extra bytes (three times more than the original data! ).

Java class

Now we know how to calculate Java Object, Java Primitive, and Java Primitive Wrapper and Arrays. Any class in Java is nothing more than an object that mixes all the mentioned components:

Header (8 or 12 bytes of a 32 hip 64-bit operating system).

Primitive (type bytes depend on the original type).

Object / class / array (4-byte reference size).

Java string

Java string is a good example of a class, so in addition to header and hash, it also encapsulates the char array, so for long strings of length 500, we have:

String

Encapsulated character array

Header

8-12 bytes (32pm 64-bit operating system) header8-12 bytes (32pm 64-bit operating system) hash4 byte array length 4 bytes char [] (reference) 4 bytes 500 characters 500 * 2 bytes = 1000 bytes string size 16 or 24 bytes total array size 16 (considering gaps) + 1000 bytes = 1016 bytes total size (16 or 24) + 1016 = 1032 or 1040 bytes (for 32 and 64 bit os)

But we need to take into account that there are different implementations of the Java String class, but in general, the main size is saved by the char array.

How to calculate programmatically using the runtime check size freeMemory

The simplest but unreliable way is to compare the difference between total memory and free memory before and after memory initialization:

Long beforeUsedMem=Runtime.getRuntime () .totalMemory ()-Runtime.getRuntime () .freeMemory (); Object [] myObjArray = new Object [100000000]; long afterUsedMem=Runtime.getRuntime () .totalMemory ()-Runtime.getRuntime () .freeMemory (); use the Jol library

The best way is to use the Jol library written by Aleksey Shipilev. This solution will surprise you to find that we can easily investigate any object / primitive / array. To do this, you need to add the next Maven dependency:

Org.openjdk.jol jol-core 0.16

And provide ClassLayout.parseInstance with whatever you want to estimate:

Int primitive = 3; / / put here any class/object/primitive/array etcSystem.out.println (VM.current () .details ()); System.out.println (ClassLayout.parseInstance (primitive) .toPrintable ())

As an output, you will see:

Plain text 1

# Running 64-bit HotSpot VM.# Using compressed oop with 0-bit shift.# Using compressed klass with 3-bit shift.# Objects are 8 bytes aligned.# Field sizes by type: 4,1,1,2,2,4,4,8,8 [bytes] # Array element sizes: 4,1,1,2,2,4,4,4,8,8 [bytes] java.lang.Integer object internals:OFF SZ TYPE DESCRIPTION VALUE 0 8 (object header: mark) 0x0000000000000001 (non-biasable) Age: 0) 8 4 (object header: class) 0x200021de 124 int Integer.value 3Instance size: 16 bytesSpace losses: 0 bytes internal + 0 bytes external = 0 bytes total use Profiler

As an option, anger can use parsers (JProfiler, VM Visualizer, JConsole, etc.) to observe how much memory is consumed by this or other structure. But this solution is about analyzing memory rather than object structure. In the next paragraph, we will use JProfiler to confirm that our calculation is correct.

Make a database cache class and calculate its size

As a real-world example, we create a class to represent the data in a database table that contains 5 columns and 1.000.000 records.

Public class UserCache {public static void main (String [] args) {User [] cachedUsers = new User [1000000000]; while (true) {} private static class User {Long id; String name; / / assume 36 characters long Integer salary; Double account; Boolean isActive;}}

So now we've created 1 million users, right? Well, it doesn't matter what it is in the User class-- we just created 1m references. Memory usage: 1m * 4 bytes = 4000 KB or 4MB. It didn't even start, but paid for 4MB.

Analyze Java memory for 64-bit systems

To confirm our calculation, we execute our code and attach JProfile to it. As an alternative, you can use any other parser, such as VisualVM (which is free).

Tip: when you analyze an application, you can run GC from time to time to clean up unused objects. So the result of the analysis: we have the reference point of User [] 4m record, the size is 4000KB.

As the next step, we initialize the objects and add them to our array (the name is the unique UUID 36 length size):

For (int I = 0 position I)

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