我的测试博客文章

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值