Java直接内存读写的例子
在Hotspot JVM上,我们能够直接对内存进行读写操作。该类的allocateMemory方法用于申请分配内存,putAddress和getAddress方法用于对直接内存进行读写。
本文将通过sun.misc.Unsafe给出一个直接读写内存的例子。
注意:这只是一个例子,只是用来验证通过sun.misc.Unsafe来实现直接读写内存的可能性。但是,这样做并没有安全保证,而且稍微有点疏忽将可能导致JVM崩溃。
Unsafe类的三个方法:allocateMemory,putAddress和getAddress如下:
- /**
- * Fetches a native pointer from a given memory address. If the address is
- * zero, or does not point into a block obtained from {@link
- * #allocateMemory}, the results are undefined.
- *
- * <p> If the native pointer is less than bits wide, it is extended as
- * an unsigned number to a Java long. The pointer may be indexed by any
- * given byte offset, simply by adding that offset (as a simple integer) to
- * the long representing the pointer. The number of bytes actually read
- * from the target address maybe determined by consulting {@link
- * #addressSize}.
- *
- * @see #allocateMemory
- */
- public native long getAddress(long address);
- /**
- * Stores a native pointer into a given memory address. If the address is
- * zero, or does not point into a block obtained from {@link
- * #allocateMemory}, the results are undefined.
- *
- * <p> The number of bytes actually written at the target address maybe
- * determined by consulting {@link #addressSize}.
- *
- * @see #getAddress(long)
- */
- public native void putAddress(long address, long x);
- /// wrappers for malloc, realloc, free:
- /**
- * Allocates a new block of native memory, of the given size in bytes. The
- * contents of the memory are uninitialized; they will generally be
- * garbage. The resulting native pointer will never be zero, and will be
- * aligned for all value types. Dispose of this memory by calling {@link
- * #freeMemory}, or resize it with {@link #reallocateMemory}.
- *
- * @throws IllegalArgumentException if the size is negative or too large
- * for the native size_t type
- *
- * @throws OutOfMemoryError if the allocation is refused by the system
- *
- * @see #getByte(long)
- * @see #putByte(long, byte)
- */
- public native long allocateMemory(long bytes);
1. long allocateMemory(long bytes)
申请分配内存
2. long getAddress(long address) 和void putAddress(long address, long x)
对直接内存进行读写。
因为Unsafe这个类的访问是受限的,只有rt.jar中的类才能使用Unsafe的功能,它的构造方法是私有的,所以,我们不能通过new来创建实例。但是,可以通过反射的方法来获取Unsafe实例。
下面就是一个直接访问内存的一个例子:
- import java.lang.reflect.Field;
- import sun.misc.Unsafe;
- public class DirectMemoryAccess {
- public static void main(String[] args) {
- /*
- * Unsafe的构造函数是私有的,不能通过new来获得实例。
- *
- * 通过反射来获取
- */
- Unsafe unsafe = null;
- Field field = null;
- try {
- field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
- /*
- * private static final Unsafe theUnsafe = new Unsafe();
- *
- * 因为field的修饰符为 private static final,
- * 需要将setAccessible设置成true,否则会报java.lang.IllegalAccessException
- */
- field.setAccessible(true);
- unsafe = (Unsafe) field.get(null);
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- long oneHundred = 100;
- byte size = 1;
- /*
- * 调用allocateMemory分配内存
- */
- long memoryAddress = unsafe.allocateMemory(size);
- /*
- * 将100写入到内存中
- */
- unsafe.putAddress(memoryAddress, oneHundred);
- /*
- * 内存中读取数据
- */
- long readValue = unsafe.getAddress(memoryAddress);
- System.out.println("Val : " + readValue);
- }
- }
输出结果:
Val : 100
如果,想要查阅Unsafe的源代码,请参考下面的链接.
http://www.docjar.com/html/api/sun/misc/Unsafe.java.html
原文 转自 :http://blog.csdn.net/joe_007/article/details/38964407
Java直接内存读写的例子的更多相关文章
- 最简单的基于FFmpeg的内存读写的例子:内存转码器
===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...
- 最简单的基于FFmpeg的内存读写的例子:内存播放器
===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...
- (转)最简单的基于FFmpeg的内存读写的例子:内存播放器
ffmpeg内存播放解码 目录(?)[+] ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章 ...
- java中常见的内存泄露的例子
JAVA 中的内存泄露 Java中的内存泄露,广义并通俗的说,就是:不再会被使用的对象的内存不能被回收,就是内存泄露. Java中的内存泄露与C++中的表现有所不同. 在C++ ...
- 沉淀再出发:java的文件读写
沉淀再出发:java的文件读写 一.前言 对于java的文件读写是我们必须使用的一项基本技能,因此了解其中的原理,字节流和字符流的本质有着重要的意义. 二.java中的I/O操作 2.1.文件读写的本 ...
- 深入理解Java虚拟机内存模型
前言 本文中部分内容引用至<深入理解Java虚拟机:JVM高级特性与最佳实践(第2版)>第12章,如果有兴趣可自行深入阅读,文末放有书籍PDF版本连接. 一.物理机中的并发 物理机遇到的并 ...
- 深入理解JVM(③)学习Java的内存模型
前言 Java内存模型(Java Memory Model)用来屏蔽各种硬件和操作系统的内存访问差异,这使得Java能够变得非常灵活而不用考虑各系统间的兼容性等问题.定义Java内存模型并非一件容易的 ...
- Java对象内存布局
本文转载自Java对象内存布局 导语 首先直接抛出问题 Unsafe.getInt(obj, fieldOffset)中的fieldOffset是什么, 类似还有compareAndSwapX(obj ...
- 全网最硬核 Java 新内存模型解析与实验单篇版(不断更新QA中)
个人创作公约:本人声明创作的所有文章皆为自己原创,如果有参考任何文章的地方,会标注出来,如果有疏漏,欢迎大家批判.如果大家发现网上有抄袭本文章的,欢迎举报,并且积极向这个 github 仓库 提交 i ...
随机推荐
- Django模板语言中的Filters的使用方法
Filters可以称为过滤器.下面我们简单介绍是如何使用他的. Filters的语法: {{ value|filter_name:参数 }} Django大概提供了六十个内置过滤器,下面我们简单介绍几 ...
- str.format() 格式化数字的多种方法
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能. 基本语法是通过 {} 和 : 来代替以前的 % . format 函数可以接受不限个参数 ...
- golang 单元测试(一)
单元测试函数类型 Test(功能测试) 函数规则: 函数名: TestXxxx , 以Test为前缀.Xxxx以大写字母开头 参数类型: *testing.T func TestXxxx(t *tes ...
- Educational Codeforces Round 64 (Div. 2)
A.3*3讨论即可,注意正方形套圆套三角形只有6个点. #include<cstdio> #include<cstring> #include<iostream> ...
- mysql8.0入坑体验
正常从官网下载,并且正常安装,直到安装完成.然后用navicate连接,发现报错信息如下所示Client does not support authentication protocol reques ...
- 关于/var/log/maillog 时间和系统时间不对应的问题 -- 我出现的是日志时间比系统时间慢12个小时
那么让我们来见证奇迹的时刻吧!! 首先你要看下/etc/localtime的软连接,到哪了 一般就是这块出问题了 检查这里就绝对不会错的 对比图 : 这种情况, 删除/etc/localtime : ...
- vue实现一个评论列表
<!DOCTYPE html> <html> <head> <title>简易评论列表</title> <meta charset=& ...
- php协议任意文件读取
php://filter/read=convert.base64-encode/resource=index.php
- Eclipse 交叉编译环境
创建空工程 添加交叉编译环境 添加工程文件 如需修改交叉编译环境 Cross GCC:使用交叉编译命令编译,需要自己指定 MinGW GCC:使用make命令编译,需要有Makefile Make T ...
- arm9交叉编译工具链
Arm-linux-gcc: gcc和arm-linux-gcc的头文件并不一样. Eg. Arm-linux-ld:链接器,-T参数是使用链接器脚本. Eg. Arm-linux-readelf:读 ...