-
-
Save mbelop/6ebb11d7e583562279abfb2e3b733fa5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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