java 内存操作_java操作内存

If anyone has ever told you, you cannot write directly to memory locations in java, then they are wrong. Well, to be precise, they are half-wrong, you can write to memory locations as long as the memory is control by the JVM.

Although this is possible, I strongly recommend that you don’t do it. Failing to get your code 100% correct will cause the JVM to crash. There maybe cases where you wish to optimize you code and write to memory directly but I would only do this as a last resort.

On the Hotspot JVM, you are able to write and read directly to memory. One of the advantages of this technique is that is very fast, however it comes with no safe guards usually provided by the Java APIs. Its also not document by SUN.

Use the java class sun.misc.Unsafe, some of the methods you may be interested in are :

public native long getAddress(long address);

public native void putAddress(long address, long value);

public native long allocateMemory(long size);

public native long reallocateMemory(long l, long l1);

public native void setMemory(long l, long l1, byte b);

public native void copyMemory(long l, long l1, long l2);

You can't instantiate the class directly as it has a private constructor, so you will have to create an instance like this :

Unsafe unsafe = null;

try {

Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");

field.setAccessible(true);

unsafe = (sun.misc.Unsafe) field.get(null);

} catch (Exception e) {

throw new AssertionError(e);

}

you can then call

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class Direct {

public static void main(String... args) {

Unsafe unsafe = null;

try {

Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");

field.setAccessible(true);

unsafe = (sun.misc.Unsafe) field.get(null);

} catch (Exception e) {

throw new AssertionError(e);

}

long value = 12345;

byte size = 1;

long allocateMemory = unsafe.allocateMemory(size);

unsafe.putAddress(allocateMemory, value);

long readValue = unsafe.getAddress(allocateMemory);

System.out.println("read value : " + readValue);

}

}

this will output :

read value : 12345

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-12-29 00:57

浏览 4747

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值