import sun.misc.Unsafe; | |
import java.nio.*; | |
import java.lang.reflect.Constructor; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Modifier; | |
import java.security.AccessController; | |
import java.security.PrivilegedExceptionAction; | |
public class SimpleTest3 | |
{ | |
public static final Unsafe UNSAFE; | |
public static final long BYTE_BUFFER_ADDRESS_FIELD_OFFSET; | |
static { | |
Unsafe unsafe = null; | |
try { | |
Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor(); | |
unsafeConstructor.setAccessible(true); | |
unsafe = unsafeConstructor.newInstance(); | |
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); | |
theUnsafe.setAccessible(true); | |
unsafe = (Unsafe) theUnsafe.get(null); | |
BYTE_BUFFER_ADDRESS_FIELD_OFFSET = unsafe.objectFieldOffset(Buffer.class.getDeclaredField("address")); | |
} catch (final Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
UNSAFE = unsafe; | |
} | |
public static long address(final ByteBuffer buffer) | |
{ | |
if (!buffer.isDirect()) | |
throw new IllegalArgumentException("buffer.isDirect() must be true"); | |
return UNSAFE.getLong(buffer, BYTE_BUFFER_ADDRESS_FIELD_OFFSET); | |
} | |
public static void main(String[] args) | |
{ | |
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(128); | |
assert byteBuffer.isDirect() == true; | |
long addressOffset = address(byteBuffer); | |
System.out.println("addressOffset=" + addressOffset); | |
UNSAFE.putInt(null, addressOffset + 0, 42); | |
if (UNSAFE.getInt(null, addressOffset + 0) == 42) | |
System.out.println("The magic of unsafe."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment