当前位置: 首页 > news >正文

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 messageunparkThread(); // Unpark the thread}
  1. 可见性操作:提供了一些方法来保证线程间的可见性。

      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());}

  2. 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);}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 封装websocket
  • 代码随想录算法训练营day50 | 深度优先搜索理论基础、98. 所有可达路径、广度优先搜索理论基础
  • 教程:使用Python裁剪TIF影像为多个自定义大小的小块(分割栅格)
  • K8S 探针
  • 创建、使用、删除 数据库
  • web的发展历史,互联网和万维网的关系
  • QT自定义信号槽
  • python 压力测试脚本
  • 主要内容和创新点、研究方法和实现途径这两个概念在学术研究和技术开发中各有侧重点
  • Matplotlib基本操作
  • kubernetes的pod基础
  • MySQL 数据库管理
  • 微信小程序——弹出隐私指引教程(含代码)
  • C:每日一练:单身狗(2.0版本)
  • 【JAVA CORE_API】Day18 网络编程、线程、在线聊天室v1.0
  • 《深入 React 技术栈》
  • 「前端早读君006」移动开发必备:那些玩转H5的小技巧
  • 2017-08-04 前端日报
  • Codepen 每日精选(2018-3-25)
  • Git同步原始仓库到Fork仓库中
  • gulp 教程
  • JavaScript 奇技淫巧
  • js继承的实现方法
  • js写一个简单的选项卡
  • JS学习笔记——闭包
  • Linux快速复制或删除大量小文件
  • React 快速上手 - 07 前端路由 react-router
  • Vue 重置组件到初始状态
  • 阿里云应用高可用服务公测发布
  • 对JS继承的一点思考
  • 复习Javascript专题(四):js中的深浅拷贝
  • 高程读书笔记 第六章 面向对象程序设计
  • 快速体验 Sentinel 集群限流功能,只需简单几步
  • 爬虫进阶 -- 神级程序员:让你的爬虫就像人类的用户行为!
  • 设计模式 开闭原则
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • 优秀架构师必须掌握的架构思维
  • 原生Ajax
  • 源码安装memcached和php memcache扩展
  • 正则与JS中的正则
  • MyCAT水平分库
  • ​configparser --- 配置文件解析器​
  • ​zookeeper集群配置与启动
  • # linux 中使用 visudo 命令,怎么保存退出?
  • #define,static,const,三种常量的区别
  • #考研#计算机文化知识1(局域网及网络互联)
  • %check_box% in rails :coditions={:has_many , :through}
  • (1)SpringCloud 整合Python
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (附源码)流浪动物保护平台的设计与实现 毕业设计 161154
  • (每日一问)操作系统:常见的 Linux 指令详解
  • (心得)获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
  • (转)Android中使用ormlite实现持久化(一)--HelloOrmLite
  • (转)ObjectiveC 深浅拷贝学习
  • (转)视频码率,帧率和分辨率的联系与区别