How many bytes does a Java new Object() occupy?

How many bytes does Java Object obj = new Object() occupy?

There is no sizeofoperator similar to C in Java . How to get the number of bytes actually occupied by an object?

method one:

A more convenient way is to observe by starting jvisualvm that comes with jdk.

Write a test class first

public class ObjectSizeInfo {
	
	public static void main(String[] args) throws IOException {
		ObjectSizeInfo sizes=new ObjectSizeInfo();
		System.in.read();
	}

}

As you can see, 1 object occupies 16 bytes

supplement

Since an Object object occupies 16 bytes, what are the contents stored in these 16 bytes?

  • The first 8 bytes are the object header, also called markword, which records the various states of the object being locked (lock upgrade) and garbage collection related information.
  • The next 4 bytes (below 4G heap memory; or less than 32G, with ClassPointer pointer compression enabled, otherwise 8 bytes ) is a pointer to the Class object to which the object belongs.
  • The next 4 bytes are padding for 8-byte alignment.

Check whether pointer compression is turned on:

C:\Users\User>java -XX:+PrintFlagsFinal | find "UseCompressed"
     bool UseCompressedClassPointers               := true                                {lp64_product}
     bool UseCompressedOops                        := true                                {lp64_product}

UseCompressedClassPointers: compression options for class object pointers.

UseCompressedOops (oops-Ordinary Object Pointers): Common object pointer compression option.

Method Two

Use the jol (Java Object Layout) library provided by OpenJDK for observation.
Maven introduces dependencies:

<!-- https://mvnrepository.com/artifact/org.openjdk.jol/jol-core -->
<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.14</version>
    <scope>provided</scope>
</dependency>
public class ObjectSizeInfo {
	
	public static void main(String[] args) throws IOException {
		ObjectSizeInfo sizes=new ObjectSizeInfo();
		String layout = ClassLayout.parseInstance(sizes).toPrintable();
		System.out.println(layout);
	}

}

Explanation: The instance object occupies 16 bytes.

Attached drawing:Object memory layout

Guess you like

Origin blog.csdn.net/GoSaint/article/details/110920114