JAVA Unsafe 类介绍

Unsafe 类提供了低级别、不安全的原始操作,这些操作可以直接访问内存。由于这些操作非常强大,可以直接操作内存,因此也非常危险。如果使用不当,可能会导致严重的内存泄露问题。

Unsafe 类的主要功能包括:

  1. 直接内存访问:可以分配和释放内存,创建和操作对象。
复制代码
  private static final int BUFFER_SIZE = 1024;
 
    // 获取Unsafe实例
    private static final Unsafe unsafe = getUnsafeInstance();
 
    // 分配内存
    private static final long buffer = unsafe.allocateMemory(BUFFER_SIZE);
 
    private static Unsafe getUnsafeInstance() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static void main(String[] args) {
        // 使用直接内存
        unsafe.setMemory(buffer, BUFFER_SIZE, (byte) 0);
 
        // ... 进行其他操作
 
        // 释放内存
        unsafe.freeMemory(buffer);
    }
  1. 线程和锁:提供了线程的挂起和恢复、定时等待等操作。

    复制代码
     private static final Unsafe UNSAFE;
     private static final long THREAD_PTR;
    
     static {
         try {
             Field field = Unsafe.class.getDeclaredField("theUnsafe");
             field.setAccessible(true);
             UNSAFE = (Unsafe) field.get(null);
    
             Thread currentThread = Thread.currentThread();
             THREAD_PTR = UNSAFE.getLong(currentThread, UNSAFE.objectFieldOffset(Thread.class.getDeclaredField("threadStatus")));
         } catch (Exception e) {
             throw new Error(e);
         }
     }
    
     public static void parkThread() {
         UNSAFE.park(false, 0L);
     }
    
     public static void unparkThread() {
         UNSAFE.unpark(Thread.currentThread());
     }
    
     public static void main(String[] args) throws InterruptedException {
         Thread thread = new Thread(() -> {
             System.out.println("Thread is going to be parked");
             parkThread();
             System.out.println("Thread is unparked");
         });
    
         thread.start();
         Thread.sleep(1000); // Wait for the thread to start and print the first message
         unparkThread(); // Unpark the thread
     }
  2. 可见性操作:提供了一些方法来保证线程间的可见性。

    复制代码
      private static final Unsafe UNSAFE;
        private static final long VALUE_OFFSET;
     
        static {
            try {
                Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
                theUnsafe.setAccessible(true);
                UNSAFE = (Unsafe) theUnsafe.get(null);
     
                VALUE_OFFSET = UNSAFE.objectFieldOffset(
                    UnsafeVisibilityExample.class.getDeclaredField("value"));
            } catch (Exception e) {
                throw new Error(e);
            }
        }
     
        private volatile int value = 0;
     
        public void increaseValue() {
            UNSAFE.putOrderedInt(this, VALUE_OFFSET, value + 1);
        }
     
        public int getValue() {
            return value;
        }
     
        public static void main(String[] args) throws InterruptedException {
            UnsafeVisibilityExample example = new UnsafeVisibilityExample();
     
            Thread t1 = new Thread(() -> {
                for (int i = 0; i < 10000; i++) {
                    example.increaseValue();
                }
            });
     
            Thread t2 = new Thread(() -> {
                while (example.getValue() < 10000) {
                    // Busy wait until condition is met
                }
            });
     
            t1.start();
            t2.start();
     
            t1.join();
            t2.join();
     
            System.out.println("Value after both threads have finished: " + example.getValue());
        }
  3. CAS 操作:提供了 CompareAndSwap 等原子操作。

    复制代码
     private static final Unsafe UNSAFE;
     private static final long VALUE_OFFSET;
    
     static {
         try {
             Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
             theUnsafe.setAccessible(true);
             UNSAFE = (Unsafe) theUnsafe.get(null);
    
             VALUE_OFFSET = UNSAFE.objectFieldOffset(UnsafeTest.class.getDeclaredField("value"));
         } catch (Exception e) {
             throw new Error(e);
         }
     }
    
     private volatile int value;
    
     public static void main(String[] args) {
         UnsafeTest unsafeTest = new UnsafeTest();
         unsafeTest.value = 10;
    
         System.out.println("Before: " + unsafeTest.value);
    
         boolean success = UNSAFE.compareAndSwapInt(unsafeTest, VALUE_OFFSET, 10, 20);
    
         System.out.println("Success: " + success);
         System.out.println("After: " + unsafeTest.value);
     }
相关推荐
Brookty3 分钟前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
能工智人小辰17 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT17 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄20 分钟前
设计模式之外观模式
java·设计模式·外观模式
LL.。41 分钟前
同步回调和异步回调
开发语言·前端·javascript
好名字更能让你们记住我1 小时前
Linux多线程(十二)之【生产者消费者模型】
linux·运维·服务器·jvm·windows·centos
0wioiw01 小时前
Python基础(吃洋葱小游戏)
开发语言·python·pygame
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
栗子~~1 小时前
Python实战- Milvus 向量库 使用相关方法demo
开发语言·python·milvus
狐凄1 小时前
Python实例题:基于 Flask 的在线聊天系统
开发语言·python