Skip to content

Instantly share code, notes, and snippets.

@Frontear
Last active September 16, 2019 14:42
Show Gist options
  • Select an option

  • Save Frontear/0fead4602216099a7fd807b31cfd3276 to your computer and use it in GitHub Desktop.

Select an option

Save Frontear/0fead4602216099a7fd807b31cfd3276 to your computer and use it in GitHub Desktop.
Working with sun.misc.Unsafe: How to allocate, store, and view information
package org.frontear
fun main() {
val unsafe = SunUtils.getUnsafe()!!
val str = "Hello World"
val int = Int.MAX_VALUE
val address = unsafe.allocateMemory((Int.SIZE_BYTES + Char.SIZE_BYTES * str.length).toLong()) // allocate enough memory for our objects. Notice how we don't allocate for the \0 in strings, as we don't need it in this case, but might in other cases
unsafe.putInt(address, int) // we don't need to offset, since the address is starting from it's beginning point
for (i in 0 until str.length) {
val char = str[i]
unsafe.putChar((address + Int.SIZE_BYTES.toLong()) + (Char.SIZE_BYTES * i).toLong(), char) // offset by the int + whatever character we are on.
}
println(unsafe.getInt(address)) // we once again do not need to offset by the int size
for (i in 0 until str.length) {
print(unsafe.getChar((address + Int.SIZE_BYTES.toLong()) + (Char.SIZE_BYTES * i).toLong())) // offset and read all characters from the block of memory
}
unsafe.freeMemory(address) // this is considered good practice. Although it does very little to keep it here, since when the program ends, the kernel will recollect the memory, however it's important in other programs, so get used to it
}
package org.frontear.utils;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class SunUtils {
private SunUtils() {
throw new UnsupportedOperationException(String.format("Cannot construct %s", SunUtils.class.getSimpleName()));
}
private static Unsafe unsafe;
static {
try {
final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
}
catch (IllegalAccessException | NoSuchFieldException e) {
throw new Error(); // bad bad
}
}
public static Unsafe getUnsafe() {
return unsafe;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment