在Hotspot JVM上,我们能够直接对内存进行读写操作。该类的allocateMemory方法用于申请分配内存,putAddress和getAddress方法用于对直接内存进行读写。

本文将通过sun.misc.Unsafe给出一个直接读写内存的例子。

注意:这只是一个例子,只是用来验证通过sun.misc.Unsafe来实现直接读写内存的可能性。但是,这样做并没有安全保证,而且稍微有点疏忽将可能导致JVM崩溃。

Unsafe类的三个方法:allocateMemory,putAddress和getAddress如下:

  1. /**
  2. * Fetches a native pointer from a given memory address.  If the address is
  3. * zero, or does not point into a block obtained from {@link
  4. * #allocateMemory}, the results are undefined.
  5. *
  6. * <p> If the native pointer is less than  bits wide, it is extended as
  7. * an unsigned number to a Java long.  The pointer may be indexed by any
  8. * given byte offset, simply by adding that offset (as a simple integer) to
  9. * the long representing the pointer.  The number of bytes actually read
  10. * from the target address maybe determined by consulting {@link
  11. * #addressSize}.
  12. *
  13. * @see #allocateMemory
  14. */
  15. public native long getAddress(long address);
  16. /**
  17. * Stores a native pointer into a given memory address.  If the address is
  18. * zero, or does not point into a block obtained from {@link
  19. * #allocateMemory}, the results are undefined.
  20. *
  21. * <p> The number of bytes actually written at the target address maybe
  22. * determined by consulting {@link #addressSize}.
  23. *
  24. * @see #getAddress(long)
  25. */
  26. public native void putAddress(long address, long x);
  27. /// wrappers for malloc, realloc, free:
  28. /**
  29. * Allocates a new block of native memory, of the given size in bytes.  The
  30. * contents of the memory are uninitialized; they will generally be
  31. * garbage.  The resulting native pointer will never be zero, and will be
  32. * aligned for all value types.  Dispose of this memory by calling {@link
  33. * #freeMemory}, or resize it with {@link #reallocateMemory}.
  34. *
  35. * @throws IllegalArgumentException if the size is negative or too large
  36. *         for the native size_t type
  37. *
  38. * @throws OutOfMemoryError if the allocation is refused by the system
  39. *
  40. * @see #getByte(long)
  41. * @see #putByte(long, byte)
  42. */
  43. 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实例。

下面就是一个直接访问内存的一个例子:

  1. import java.lang.reflect.Field;
  2. import sun.misc.Unsafe;
  3. public class DirectMemoryAccess {
  4. public static void main(String[] args) {
  5. /*
  6. * Unsafe的构造函数是私有的,不能通过new来获得实例。
  7. *
  8. *  通过反射来获取
  9. */
  10. Unsafe unsafe = null;
  11. Field field = null;
  12. try {
  13. field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
  14. /*
  15. * private static final Unsafe theUnsafe = new Unsafe();
  16. *
  17. * 因为field的修饰符为 private static final,
  18. * 需要将setAccessible设置成true,否则会报java.lang.IllegalAccessException
  19. */
  20. field.setAccessible(true);
  21. unsafe = (Unsafe) field.get(null);
  22. } catch (SecurityException e) {
  23. // TODO Auto-generated catch block
  24. e.printStackTrace();
  25. } catch (NoSuchFieldException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. } catch (IllegalArgumentException e) {
  29. // TODO Auto-generated catch block
  30. e.printStackTrace();
  31. } catch (IllegalAccessException e) {
  32. // TODO Auto-generated catch block
  33. e.printStackTrace();
  34. }
  35. long oneHundred = 100;
  36. byte size = 1;
  37. /*
  38. * 调用allocateMemory分配内存
  39. */
  40. long memoryAddress = unsafe.allocateMemory(size);
  41. /*
  42. * 将100写入到内存中
  43. */
  44. unsafe.putAddress(memoryAddress, oneHundred);
  45. /*
  46. * 内存中读取数据
  47. */
  48. long readValue = unsafe.getAddress(memoryAddress);
  49. System.out.println("Val : " + readValue);
  50. }
  51. }

输出结果: 
Val : 100

如果,想要查阅Unsafe的源代码,请参考下面的链接. 
http://www.docjar.com/html/api/sun/misc/Unsafe.java.html

原文 转自 :http://blog.csdn.net/joe_007/article/details/38964407

Java直接内存读写的例子的更多相关文章

  1. 最简单的基于FFmpeg的内存读写的例子:内存转码器

    ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...

  2. 最简单的基于FFmpeg的内存读写的例子:内存播放器

    ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...

  3. (转)最简单的基于FFmpeg的内存读写的例子:内存播放器

    ffmpeg内存播放解码 目录(?)[+] ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章 ...

  4. java中常见的内存泄露的例子

    JAVA 中的内存泄露     Java中的内存泄露,广义并通俗的说,就是:不再会被使用的对象的内存不能被回收,就是内存泄露.     Java中的内存泄露与C++中的表现有所不同.     在C++ ...

  5. 沉淀再出发:java的文件读写

    沉淀再出发:java的文件读写 一.前言 对于java的文件读写是我们必须使用的一项基本技能,因此了解其中的原理,字节流和字符流的本质有着重要的意义. 二.java中的I/O操作 2.1.文件读写的本 ...

  6. 深入理解Java虚拟机内存模型

    前言 本文中部分内容引用至<深入理解Java虚拟机:JVM高级特性与最佳实践(第2版)>第12章,如果有兴趣可自行深入阅读,文末放有书籍PDF版本连接. 一.物理机中的并发 物理机遇到的并 ...

  7. 深入理解JVM(③)学习Java的内存模型

    前言 Java内存模型(Java Memory Model)用来屏蔽各种硬件和操作系统的内存访问差异,这使得Java能够变得非常灵活而不用考虑各系统间的兼容性等问题.定义Java内存模型并非一件容易的 ...

  8. Java对象内存布局

    本文转载自Java对象内存布局 导语 首先直接抛出问题 Unsafe.getInt(obj, fieldOffset)中的fieldOffset是什么, 类似还有compareAndSwapX(obj ...

  9. 全网最硬核 Java 新内存模型解析与实验单篇版(不断更新QA中)

    个人创作公约:本人声明创作的所有文章皆为自己原创,如果有参考任何文章的地方,会标注出来,如果有疏漏,欢迎大家批判.如果大家发现网上有抄袭本文章的,欢迎举报,并且积极向这个 github 仓库 提交 i ...

随机推荐

  1. Django模板语言中的Filters的使用方法

    Filters可以称为过滤器.下面我们简单介绍是如何使用他的. Filters的语法: {{ value|filter_name:参数 }} Django大概提供了六十个内置过滤器,下面我们简单介绍几 ...

  2. str.format() 格式化数字的多种方法

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能. 基本语法是通过 {} 和 : 来代替以前的 % . format 函数可以接受不限个参数 ...

  3. golang 单元测试(一)

    单元测试函数类型 Test(功能测试) 函数规则: 函数名: TestXxxx , 以Test为前缀.Xxxx以大写字母开头 参数类型: *testing.T func TestXxxx(t *tes ...

  4. Educational Codeforces Round 64 (Div. 2)

    A.3*3讨论即可,注意正方形套圆套三角形只有6个点. #include<cstdio> #include<cstring> #include<iostream> ...

  5. mysql8.0入坑体验

    正常从官网下载,并且正常安装,直到安装完成.然后用navicate连接,发现报错信息如下所示Client does not support authentication protocol reques ...

  6. 关于/var/log/maillog 时间和系统时间不对应的问题 -- 我出现的是日志时间比系统时间慢12个小时

    那么让我们来见证奇迹的时刻吧!! 首先你要看下/etc/localtime的软连接,到哪了 一般就是这块出问题了 检查这里就绝对不会错的 对比图 : 这种情况, 删除/etc/localtime : ...

  7. vue实现一个评论列表

    <!DOCTYPE html> <html> <head> <title>简易评论列表</title> <meta charset=& ...

  8. php协议任意文件读取

    php://filter/read=convert.base64-encode/resource=index.php

  9. Eclipse 交叉编译环境

    创建空工程 添加交叉编译环境 添加工程文件 如需修改交叉编译环境 Cross GCC:使用交叉编译命令编译,需要自己指定 MinGW GCC:使用make命令编译,需要有Makefile Make T ...

  10. arm9交叉编译工具链

    Arm-linux-gcc: gcc和arm-linux-gcc的头文件并不一样. Eg. Arm-linux-ld:链接器,-T参数是使用链接器脚本. Eg. Arm-linux-readelf:读 ...