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 use Unsafe class in java

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

Share

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

This article mainly introduces how to use the Unsafe class in java, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

The Unsafe class gives Java the ability to manipulate memory space like C pointers, but it also introduces pointer problems. Excessive use of the Unsafe class increases the chance of errors, so Java officials do not recommend it, and official documentation is almost non-existent. Oracle is planning to remove the Unsafe class from Java 9, and if that happens, it would be too big an impact.

I. Brief introduction

First of all in Oracle Jdk8 can not get to sun.misc package source code, want to see this package source code can be downloaded directly openjdk.

1. Preparatory work

openjdk source code I downloaded is openjdk-8u40-src-b25-10_feb_2015, there is a need to private letter me, if I am a fan of the public number, I will directly attach this Baidu cloud resources. After downloading, we can import our eclipse directly.

Unsafe class Unsafe class Unsafe class

windows->preference->installed jres-> check jre->edit->rt.jar->source attachment->external folders->openjdk source path. At this point you can check out the source code for our Unsafe class.

2. Introduction

If you learn some Java concurrency package inside the class source code, then this Unsafe class must not be unfamiliar, the entire Java concurrency package is the core of the underlying implementation of it, a long time ago rumored that this class will be removed in jdk9, in fact, if removed then a large number of frameworks will disappear, such as the famous Netty framework. When jdk9 finally appeared, it was only improved and optimized. But again, this illustrates the importance of this class.

Why is it half angel and half devil? To answer this question, we have to explain it in terms of its characteristics.

(1)Unsafe class makes Java have the ability to operate memory space like C language pointers, once it can directly operate memory, this also means (1) not managed by jvm, which means it cannot be GC, we need to manually GC, a little careless will appear memory leak.

(2) Many methods of Unsafe must provide the original address (memory address) and the address of the replaced object. The offset must be calculated by itself. Once a problem occurs, it is a JVM crash level exception, which will cause the entire JVM instance to crash.

(3)Direct memory operation also means that it is faster and can improve efficiency well under high concurrency conditions.

Therefore, from the above three perspectives, although the efficiency is improved to a certain extent, it also brings the insecurity of the pointer.

Below we dive into the source code to see what methods are provided to manipulate memory directly.

Second, source code analysis

There are 82 public native methods in Unsafe, and dozens of other methods based on these 82 public native methods. These methods can be broadly grouped into the following categories:

(1)initialization operation

(2)operand attribute

(3)manipulating array elements

(4)memory management

(5)memory barrier

(6)Thread suspend and resume

(7)CAS mechanism

Here is a rough analysis of these methods.

1, initialization

//1, Register native method, Yes Unsafe class can operate C language private static native void registerNatives();static { registerNatives(); sun.reflect. Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");}//2. constructor private Unsafe() {}//3. initializer private static final Unsafe theUnsafe = new Unsafe();//4. initializer @ CallerSensitivePublic Unsafe getUnsafe() { Class> caller = Reflection.getCallerClass(); if (! VM.isSystemDomainLoader(caller.getClassLoader())) throw new SecurityException("Unsafe"); return theUnsafe;}

Here we see that the initialization method of Unsafe is mainly implemented through the singleton mode of getUnsafe method, calling JVM local methods registerNatives() and sun.reflect.Reflection, and judging whether the currently called class is loaded by the BootStrap classLoader through getCallerClass of Reflection, otherwise throwing a SecurityException. This also proves the problem that only classes loaded by the BootStrap classLoader can invoke methods in that class.

2. Operation attribute method

(1)public native Object getObject(Object o, long offset);

Gets a reference value from a given Java variable. This is actually getting the value of the attribute offset in a Java object o, which breaks the suppression of modifiers, that is, ignoring the private, protected, and default modifiers. Similar methods are getInt, getDouble, and so on. There is also the putObject method.

(2)public native Object getObjectVolatile(Object o, long offset);

Forces attribute values to be fetched from main memory. Similar methods are getIntVolatile, getDoubleVolatile, and so on. There is also putObjectVolatile.

(3)public native void putOrderedObject(Object o, long offset, Object x);

Set the value of Object type field corresponding to offset address offset in o object to the specified value x. This is an ordered or delayed putObjectVolatile method, and there is no guarantee that the value change will be immediately seen by other threads. Use only if field is volatile and expected to be modified. Similar methods are putOrderedInt and putOrderedLong.

(4)public native long staticFieldOffset(Field f);

Returns the location (offset address) of a given static attribute in its class's storage allocation.

(5)public native long objectFieldOffset(Field f);

Returns the location (offset address) of a given nonstatic attribute in its class's storage allocation.

(6)public native Object staticFieldBase(Field f);

Returns the location of a given static attribute, used with the staticFieldOffset method.

3. Operation array

(1)public native int arrayBaseOffset(Class arrayClass);

Returns the offset address of the first element of an array type (base offset address).

(2)public native int arrayIndexScale(Class arrayClass);

Returns the increment of the offset address between elements in an array.

These two methods can be used together to locate the address of any element.

4. Memory management

(1)public native int addressSize();

Gets the size of the local pointer (in bytes), usually 4 or 8. The constant ADDRESS_SIZE calls this method.

(2)public native int pageSize();

Gets the number of pages in local memory, which is a power of two.

(3)public native long allocateMemory(long bytes);

Allocate a new block of local memory, specify the size of the memory block (in bytes) by bytes, and return the address of the newly opened memory.

(4)public native long reallocateMemory(long address, long bytes);

Resize the local memory block by specifying the memory address address, and specify the size of the memory block by bytes (in bytes).

(5)public native void setMemory(Object o, long offset, long bytes, byte value);

Sets all bytes in a given memory block to a fixed value (usually 0).

5. Thread suspension and resumption

(1)public native void unpark(Object thread);

Releases a block on a thread created by park. Because of its insecurity, threads must be guaranteed to survive.

(2)public native void park(boolean isAbsolute, long time);

Blocks the current thread until the unpark method is called.

6. Memory barrier

(1)public native void loadFence();

All read operations prior to this method must complete before the load barrier.

(2)public native void storeFence();

All write operations prior to this method must complete before the store barrier

(3)public native void fullFence();

All read and write operations before this method must be performed before the full barrier, which is equivalent to the combination of the above two (load barrier and store barrier).

7. CAS mechanism

public final native boolean compareAndSwapObject( Object o, long offset, Object expected, Object x);public final native boolean compareAndSwapInt( Object o, long offset,int expected, int x);public final native boolean compareAndSwapLong( Object o, long offset, long expected,long x);

This Unsafe class is actually running through the entire java package system, whether you look at the atomic package or lock package at the bottom of such a class, we need to remember not every method, but the title of the above seven categories. That is, what specific function it has.

III. Use

The source code that has been said for so long is introduced here, because the official does not recommend us to use it, that is to say, we cannot directly create an Unsafe class, so how do we use it? A long time ago I wrote an article introducing java reflection mechanism, yes, this is the reflection mechanism, cattle can not. Unsafe can be obtained by reflection mechanism.

public class UnsafeTest { public static void main(String[] args) throws Exception { //theUnsafe here is theUnsafe in our source code Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); Unsafe unsafe = (Unsafe) theUnsafe.get(null); //1. Create an object instance Author author = (Author) unsafe.allocateInstance(Author.class); //2. Properties of the operation object Field ageField = Author.class.getDeclaredField("age"); long fieldOffset = unsafe.objectFieldOffset(ageField); //3, operation array String[] strings = new String[]{"1", "2", "3"}; long i = unsafe.arrayBaseOffset(String[].class); //4, operating memory long address = unsafe.allocateMemory(8L); }}

Thank you for reading this article carefully. I hope the article "How to use Unsafe class in java" shared by Xiaobian will be helpful to everyone. At the same time, I hope you will support it a lot. Pay attention to the industry information channel. More relevant knowledge is waiting for you 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.

Share To

Development

Wechat

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

12
Report