How to rethrow a checked exceptions without changing your method signature or wrapping them
How to write to Direct Memory Locations in Java
How to schema check xml via JAXB
How to improve perforamance of JAXB
JVM Garbage Collector Overview
CXF Endpoint Configuration in Java
timestamp/version from mvn to flex
how-to-load-all-the-resources-from-within-a-package-of-your-jar
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 your 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 documented by SUN.
Use the java class sun.misc.Unsafe, some of the methods you may be interested in are :
publicnativelonggetByte(longaddress);publicnativevoidputByte(longaddress,bytevalue);publicnativelonggetLong(longaddress);publicnativevoidputLong(longaddress,longvalue);publicnativelongallocateMemory(longsize);publicnativelongreallocateMemory(longl,longl1);publicnativevoidsetMemory(longl,longl1,byteb);publicnativevoidcopyMemory(longl,longl1,longl2);
You can't instantiate the class directly as it has a private constructor, so you will have to create an instance like this :
Unsafeunsafe =null;try{Fieldfield =sun.misc.Unsafe.class.getDeclaredField("theUnsafe");field.setAccessible(true);unsafe =(sun.misc.Unsafe)field.get(null);}catch(Exceptione){thrownewAssertionError(e);}
you can then call
importjava.lang.reflect.Field;importsun.misc.Unsafe;publicclassDirect{publicstaticvoidmain(String...args){Unsafeunsafe =null;try{Fieldfield =sun.misc.Unsafe.class.getDeclaredField("theUnsafe");field.setAccessible(true);unsafe =(sun.misc.Unsafe)field.get(null);}catch(Exceptione){thrownewAssertionError(e);}longvalue =12345;bytesize =8;// a long is 64 bits (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)longallocateMemory =unsafe.allocateMemory(size);unsafe.putLong(allocateMemory,value);longreadValue =unsafe.getLong(allocateMemory);System.out.println("read value :" +readValue);}}
this will output :
read value : 12345