Java Non-open source unsafe class

Source: Internet
Author: User
Tags volatile

0. Preface

The unsafe class can provide us with an efficient and thread-safe way to manipulate variables, dealing directly with memory data.

1. How to obtain unsafe entities
private static Unsafe getUnsafeInstance() throws SecurityException,        NoSuchFieldException, IllegalArgumentException,        IllegalAccessException {        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");        theUnsafeInstance.setAccessible(true);        return (Unsafe) theUnsafeInstance.get(Unsafe.class);}

This method can get an object's property relative to the object's offset in memory, so that we can find this property in the object memory based on that offset.

long objectOffset = unsafe.objectFieldOffset(User.class.getDeclaredField("value"));Object value = unsafe.getObject(new User(), objectOffset);
//获取静态字段的偏移量unsafe.staticFieldOffset(User.class.getDeclaredField("value"));
2. Common Methods Introduction 2.1 compareandswapint (thread-safe)
/*** 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。*  * @param obj 需要更新的对象* @param offset obj中整型field的偏移量* @param expect 希望field中存在的值* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值* @return 如果field的值被更改返回true*/  public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);
2.2 Compareandswapobject is the same as the above method function, but is a variable of type Object
public native boolean compareAndSwapObject(Object obj, long offset, Object expect, Object update);
2.3 Putorderedint Set the value and write to main memory immediately, the variable must be of type volatile
/*** 设置 volatile 类型到int值*  * @param obj 需要更新的对象* @param offset obj中整型field的偏移量* @param expect 希望field中存在的值*/void sun.misc.Unsafe.putOrderedInt(Object obj, long offset, int expect)

Reference:
Https://www.cnblogs.com/daxin/p/3366606.html

Java Non-open source unsafe class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.