一、 What is Java Unsafe?

Java Unsafe is an internal class in Java that provides many methods to access underlying memory. Java Unsafe is a class that contains many methods related to memory access. With Java Unsafe, you can use Java code to achieve the effects of C/C++code.

Unsafe is loaded by the class loader at JVM startup and can be used at runtime, but Java reflection is required to use the methods and fields in the Unsafe class. This is a security issue with Java Unsafe, which may cause applications to crash at runtime. Therefore, many Java developers do not like to use Unsafe in the JVM.

二、 Creating objects using Java Unsafe

We need to follow the following steps when creating objects using Java Unsafe:

1. Use reflection to obtain Unsafe instances


  

  

 

2. Allocate memory

We need to use the allocateMemory() method of the Unsafe instance to allocate memory:


  

  

We allocated 24 bytes of memory and stored its address in the pointer variable pointer.

 

3. Initialize Object

We use the putXXX() method of the Unsafe instance to store the values in the newly allocated memory block:


  

  


The above code example uses the putInt method to store three integers in the newly allocated memory block. This memory block can be referenced as part of the object when needed.

4. Instantiate objects

We use the allocateInstance() method of the Unsafe instance to instantiate the object, which uses reflection to construct the object:


  

  


This code example instantiates an object using the allocateInstance() method instead of using Java's new operator. Since we have allocated memory and stored the state of the object, this method does not need to allocate memory again, but only needs to place the object's metadata in the newly allocated memory block. In this case, we have stored the metadata of the object in the memory block pointed to by the pointer variable pointer, and we can use pointers to bind the metadata with the object. If you have already set all fields to the correct values using the putXXX() method, you can actually instantiate the object by converting the pointer to an object reference.

 

三、Problems with Java Unsafe

 

1. Instability

Java Unsafe is an unstable API that may become unusable during updates or JDK version changes. Unsafe is the use of Java reflection to manipulate private fields and methods, which is unstable and may no longer be effective when the Java library or JVM changes.

2. Memory leakage


There is a risk of memory leakage when using memory allocation in Java Unsafe. We use garbage collection in Java to free memory, but using Unsafe to create unmanaged objects may cause memory leaks.

3. Security risks

Java Unsafe allows Java developers to bypass the security architecture of the Java runtime environment and access underlying system resources, which can pose potential security risks.