How To Write Directly to a Memory Locations In Java
http://robaustin.wikidot.com/how-to-write-to-direct-memory-locations-in-java
http://robaustin.wikidot.com/how-to-write-to-direct-memory-locations-in-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