当前位置:网站首页>JUC Unsafe
JUC Unsafe
2022-06-13 09:00:00 【Q z1997】
概述
Unsafe 对象提供了非常底层的,操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得
public class UnsafeAccessor {
static Unsafe unsafe;
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new Error(e);
}
}
static Unsafe getUnsafe() {
return unsafe;
}
}
Unsafe CAS 操作
@Data
class Student {
volatile int id;
volatile String name; }
Unsafe unsafe = UnsafeAccessor.getUnsafe();
Field id = Student.class.getDeclaredField("id");
Field name = Student.class.getDeclaredField("name");
// 获得成员变量的偏移量
long idOffset = UnsafeAccessor.unsafe.objectFieldOffset(id);
long nameOffset = UnsafeAccessor.unsafe.objectFieldOffset(name);
Student student = new Student();
// 使用 cas 方法替换成员变量的值
UnsafeAccessor.unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 返回 true
UnsafeAccessor.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 true
System.out.println(student);```
```java
class AtomicData {
private volatile int data;
static final Unsafe unsafe;
static final long DATA_OFFSET;
static {
unsafe = UnsafeAccessor.getUnsafe();
try {
// data 属性在 DataContainer 对象中的偏移量,用于 Unsafe 直接访问该属性
DATA_OFFSET = unsafe.objectFieldOffset(AtomicData.class.getDeclaredField("data"));
} catch (NoSuchFieldException e) {
throw new Error(e);
}
}
public AtomicData(int data) {
this.data = data;
}
public void decrease(int amount) {
int oldValue;
while(true) {
// 获取共享变量旧值,可以在这一行加入断点,修改 data 调试来加深理解
oldValue = data;
// cas 尝试修改 data 为 旧值 + amount,如果期间旧值被别的线程改了,返回 false
if (unsafe.compareAndSwapInt(this, DATA_OFFSET, oldValue, oldValue - amount)) {
return;
}
}
}
public int getData() {
return data;
}
}
边栏推荐
- 简单实现数据库链接池
- QML compilation specification
- Software Architecture Overview knowledge
- QObject::connect: Cannot queue arguments of type ‘QTextCursor‘ (Make sure ‘QTextCursor‘ is registere
- Tutorial (5.0) 02 Management * fortiedr * Fortinet network security expert NSE 5
- How to resolve "the operation cannot be completed successfully because the file contains viruses or potentially junk software
- Collection of garbled code problems in idea development environment
- Library management system based on wechat applet Rar (thesis + source code)
- H5 mobile terminal adaptation
- File upload JS
猜你喜欢

How excel adds hyperlinks to some text in a cell

4. Relationship selector (parent-child relationship, ancestor offspring relationship, brother relationship)

Redirect vulnerability analysis of network security vulnerability analysis
![[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp](/img/16/907c7c414502b22129f774fbffdafe.png)
[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp

Replace jade engine with EJS

Jfinal and swagger integration
Drill down to protobuf - Introduction

【网络安全渗透】如果你还不懂CSRF?这一篇让你彻底掌握

Basic use of cesium, including loading images, terrain, models, vector data, etc

Top+jstack to analyze the causes of excessive CPU
随机推荐
Redis fuzzy query batch deletion
ES6 module import / export summary
20211004 矩阵的子空间
Redirect vulnerability analysis of network security vulnerability analysis
Jfinal and swagger integration
20211115 任意n阶方阵均与三角矩阵(上三角或者下三角)相似
20211108 det(AB)=det(A)det(B)
Loss outputs Nan for the Nan model
Qvector shallow copy performance test
Common network problems and troubleshooting methods of gbase
[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp
Top+jstack to analyze the causes of excessive CPU
Margin:0 reason why auto does not take effect
ES6 use of dynamic attributes
Cesium view switching, locating, reading files, building data sources, entity control, model control, etc
20211028 调节和跟踪
14. class initialization, default constructor, =default
Collection of various books
Pytorch model tuning - only some layers of the pre training model are loaded
Drill down to protobuf - Introduction