Java Code Examples for jdk.internal.misc.Unsafe#getUnsafe()

The following examples show how to use jdk.internal.misc.Unsafe#getUnsafe() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GetPutBoolean.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    Test t = new Test();
    Field field = Test.class.getField("b1");

    long offset = unsafe.objectFieldOffset(field);
    assertEquals(false, unsafe.getBoolean(t, offset));
    unsafe.putBoolean(t, offset, true);
    assertEquals(true, unsafe.getBoolean(t, offset));

    boolean arrayBoolean[] = { true, false, false, true };
    int scale = unsafe.arrayIndexScale(arrayBoolean.getClass());
    offset = unsafe.arrayBaseOffset(arrayBoolean.getClass());
    for (int i = 0; i < arrayBoolean.length; i++) {
        assertEquals(unsafe.getBoolean(arrayBoolean, offset), arrayBoolean[i]);
        offset += scale;
    }
}
 
Example 2
Source File: GetPutFloat.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    Test t = new Test();
    Field field = Test.class.getField("f");

    long offset = unsafe.objectFieldOffset(field);
    assertEquals(-1.0f, unsafe.getFloat(t, offset));
    unsafe.putFloat(t, offset, 0.0f);
    assertEquals(0.0f, unsafe.getFloat(t, offset));

    long address = unsafe.allocateMemory(8);
    unsafe.putFloat(address, 1.0f);
    assertEquals(1.0f, unsafe.getFloat(address));
    unsafe.freeMemory(address);

    float arrayFloat[] = { -1.0f, 0.0f, 1.0f, 2.0f };
    int scale = unsafe.arrayIndexScale(arrayFloat.getClass());
    offset = unsafe.arrayBaseOffset(arrayFloat.getClass());
    for (int i = 0; i < arrayFloat.length; i++) {
        assertEquals(unsafe.getFloat(arrayFloat, offset), arrayFloat[i]);
        offset += scale;
    }
}
 
Example 3
Source File: GetPutAddress.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    int addressSize = unsafe.addressSize();
    // Ensure the size returned from Unsafe.addressSize is correct
    assertEquals(unsafe.addressSize(), Platform.is32bit() ? 4 : 8);

    // Write the address, read it back and make sure it's the same value
    long address = unsafe.allocateMemory(addressSize);
    unsafe.putAddress(address, address);
    long readAddress = unsafe.getAddress(address);
    if (addressSize == 4) {
      readAddress &= 0x00000000FFFFFFFFL;
    }
    assertEquals(address, readAddress);
    unsafe.freeMemory(address);
}
 
Example 4
Source File: MappedByteBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Loads this buffer's content into physical memory.
 *
 * <p> This method makes a best effort to ensure that, when it returns,
 * this buffer's content is resident in physical memory.  Invoking this
 * method may cause some number of page faults and I/O operations to
 * occur. </p>
 *
 * @return  This buffer
 */
public final MappedByteBuffer load() {
    checkMapped();
    if ((address == 0) || (capacity() == 0))
        return this;
    long offset = mappingOffset();
    long length = mappingLength(offset);
    load0(mappingAddress(offset), length);

    // Read a byte from each page to bring it into memory. A checksum
    // is computed as we go along to prevent the compiler from otherwise
    // considering the loop as dead code.
    Unsafe unsafe = Unsafe.getUnsafe();
    int ps = Bits.pageSize();
    int count = Bits.pageCount(length);
    long a = mappingAddress(offset);
    byte x = 0;
    for (int i=0; i<count; i++) {
        x ^= unsafe.getByte(a);
        a += ps;
    }
    if (unused != 0)
        unused = x;

    return this;
}
 
Example 5
Source File: CopyMemory.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    long src = unsafe.allocateMemory(LENGTH);
    long dst = unsafe.allocateMemory(LENGTH);
    assertNotEquals(src, 0L);
    assertNotEquals(dst, 0L);

    // call copyMemory() with different lengths and verify the contents of
    // the destination array
    for (int i = 0; i < LENGTH; i++) {
        unsafe.putByte(src + i, (byte)i);
        unsafe.copyMemory(src, dst, i);
        for (int j = 0; j < i; j++) {
            assertEquals(unsafe.getByte(src + j), unsafe.getByte(src + j));
        }
    }
    unsafe.freeMemory(src);
    unsafe.freeMemory(dst);
}
 
Example 6
Source File: GetPutChar.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    Test t = new Test();
    Field field = Test.class.getField("c");

    long offset = unsafe.objectFieldOffset(field);
    assertEquals('\u0000', unsafe.getChar(t, offset));
    unsafe.putChar(t, offset, '\u0001');
    assertEquals('\u0001', unsafe.getChar(t, offset));

    long address = unsafe.allocateMemory(8);
    unsafe.putChar(address, '\u0002');
    assertEquals('\u0002', unsafe.getChar(address));
    unsafe.freeMemory(address);

    char arrayChar[] = { '\uabcd', '\u00ff', '\uff00', };
    int scale = unsafe.arrayIndexScale(arrayChar.getClass());
    offset = unsafe.arrayBaseOffset(arrayChar.getClass());
    for (int i = 0; i < arrayChar.length; i++) {
        assertEquals(unsafe.getChar(arrayChar, offset), arrayChar[i]);
        offset += scale;
    }
}
 
Example 7
Source File: GetPutByte.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    Test t = new Test();
    Field field = Test.class.getField("b");

    long offset = unsafe.objectFieldOffset(field);
    assertEquals((byte)0, unsafe.getByte(t, offset));
    unsafe.putByte(t, offset, (byte)1);
    assertEquals((byte)1, unsafe.getByte(t, offset));

    long address = unsafe.allocateMemory(8);
    unsafe.putByte(address, (byte)2);
    assertEquals((byte)2, unsafe.getByte(address));
    unsafe.freeMemory(address);

    byte arrayByte[] = { -1, 0, 1, 2 };
    int scale = unsafe.arrayIndexScale(arrayByte.getClass());
    offset = unsafe.arrayBaseOffset(arrayByte.getClass());
    for (int i = 0; i < arrayByte.length; i++) {
        assertEquals(unsafe.getByte(arrayByte, offset), arrayByte[i]);
        offset += scale;
    }
}
 
Example 8
Source File: GetField.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    // Unsafe.INVALID_FIELD_OFFSET is a static final int field,
    // make sure getField returns the correct field
    Field field = Unsafe.class.getField("INVALID_FIELD_OFFSET");
    assertNotEquals(field.getModifiers() & Modifier.FINAL, 0);
    assertNotEquals(field.getModifiers() & Modifier.STATIC, 0);
    assertEquals(field.getType(), int.class);
}
 
Example 9
Source File: ClassLoader.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to atomically set a volatile field in this object. Returns
 * {@code true} if not beaten by another thread. Avoids the use of
 * AtomicReferenceFieldUpdater in this class.
 */
private boolean trySetObjectField(String name, Object obj) {
    Unsafe unsafe = Unsafe.getUnsafe();
    Class<?> k = ClassLoader.class;
    long offset;
    offset = unsafe.objectFieldOffset(k, name);
    return unsafe.compareAndSetReference(this, offset, null, obj);
}
 
Example 10
Source File: PageSize.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    int pageSize = unsafe.pageSize();

    for (int n = 1; n != 0; n <<= 1) {
        if (pageSize == n) {
            return;
        }
    }
    throw new RuntimeException("Expected pagesize to be a power of two, actual pagesize:" + pageSize);
}
 
Example 11
Source File: Reallocate.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();

    long address = unsafe.allocateMemory(1);
    assertNotEquals(address, 0L);

    // Make sure we reallocate correctly
    unsafe.putByte(address, Byte.MAX_VALUE);
    address = unsafe.reallocateMemory(address, 2);
    assertNotEquals(address, 0L);
    assertEquals(unsafe.getByte(address), Byte.MAX_VALUE);

    // Reallocating with a 0 size should return a null pointer
    address = unsafe.reallocateMemory(address, 0);
    assertEquals(address, 0L);

    // Reallocating with a null pointer should result in a normal allocation
    address = unsafe.reallocateMemory(0L, 1);
    assertNotEquals(address, 0L);
    unsafe.putByte(address, Byte.MAX_VALUE);
    assertEquals(unsafe.getByte(address), Byte.MAX_VALUE);

    // Make sure we can throw an OOME when we fail to reallocate due to OOM
    try {
        unsafe.reallocateMemory(address, 100 * 1024 * 1024 * 8);
    } catch (OutOfMemoryError e) {
        // Expected
        return;
    }
    throw new RuntimeException("Did not get expected OOM");
}
 
Example 12
Source File: NestedUnsafe2.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();

    // The anonymous class calls defineAnonymousClass creating a nested anonymous class.
    byte klassbuf2[] = InMemoryJavaCompiler.compile("TestClass2",
        "import jdk.internal.misc.Unsafe; " +
        "public class TestClass2 { " +
        "    public static void doit() throws Throwable { " +
        "        Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe(); " +
        "        Class klass2 = unsafe.defineAnonymousClass(TestClass2.class, p.NestedUnsafe2.klassbuf, new Object[0]); " +
        "        unsafe.ensureClassInitialized(klass2); " +
        "        Class[] dArgs = new Class[2]; " +
        "        dArgs[0] = String.class; " +
        "        dArgs[1] = String.class; " +
        "        try { " +
        "            klass2.getMethod(\"concat\", dArgs).invoke(null, \"CC\", \"DD\"); " +
        "        } catch (Throwable ex) { " +
        "            throw new RuntimeException(\"Exception: \" + ex.toString()); " +
        "        } " +
        "} } ",
        "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED");

    Class klass2 = unsafe.defineAnonymousClass(p.NestedUnsafe2.class, klassbuf2, new Object[0]);
    try {
        klass2.getMethod("doit").invoke(null);
        throw new RuntimeException("Expected exception not thrown");
    } catch (Throwable ex) {
        Throwable iae = ex.getCause();
        if (!iae.toString().contains(
            "IllegalArgumentException: Host class p/NestedUnsafe2 and anonymous class q/TestClass")) {
            throw new RuntimeException("Exception: " + iae.toString());
        }
    }
}
 
Example 13
Source File: NestedUnsafe.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();

    // The anonymous class calls defineAnonymousClass creating a nested anonymous class.
    byte klassbuf2[] = InMemoryJavaCompiler.compile("p.TestClass2",
        "package p; " +
        "import jdk.internal.misc.Unsafe; " +
        "public class TestClass2 { " +
        "    public static void doit() throws Throwable { " +
        "        Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe(); " +
        "        Class klass2 = unsafe.defineAnonymousClass(TestClass2.class, p.NestedUnsafe.klassbuf, new Object[0]); " +
        "        unsafe.ensureClassInitialized(klass2); " +
        "        Class[] dArgs = new Class[2]; " +
        "        dArgs[0] = String.class; " +
        "        dArgs[1] = String.class; " +
        "        try { " +
        "            klass2.getMethod(\"concat\", dArgs).invoke(null, \"CC\", \"DD\"); " +
        "        } catch (Throwable ex) { " +
        "            throw new RuntimeException(\"Exception: \" + ex.toString()); " +
        "        } " +
        "} } ",
        "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED");

    Class klass2 = unsafe.defineAnonymousClass(p.NestedUnsafe.class, klassbuf2, new Object[0]);
    try {
        klass2.getMethod("doit").invoke(null);
        throw new RuntimeException("Expected exception not thrown");
    } catch (Throwable ex) {
        Throwable iae = ex.getCause();
        if (!iae.toString().contains(
            "IllegalArgumentException: Host class p/NestedUnsafe and anonymous class q/TestClass")) {
            throw new RuntimeException("Exception: " + iae.toString());
        }
    }
}
 
Example 14
Source File: MappedByteBuffer.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Loads this buffer's content into physical memory.
 *
 * <p> This method makes a best effort to ensure that, when it returns,
 * this buffer's content is resident in physical memory.  Invoking this
 * method may cause some number of page faults and I/O operations to
 * occur. </p>
 *
 * @return  This buffer
 */
public final MappedByteBuffer load() {
    if (fd == null) {
        return this;
    }
    // no need to load a sync mapped buffer
    if (isSync()) {
        return this;
    }
    if ((address == 0) || (capacity() == 0))
        return this;
    long offset = mappingOffset();
    long length = mappingLength(offset);
    load0(mappingAddress(offset), length);

    // Read a byte from each page to bring it into memory. A checksum
    // is computed as we go along to prevent the compiler from otherwise
    // considering the loop as dead code.
    Unsafe unsafe = Unsafe.getUnsafe();
    int ps = Bits.pageSize();
    int count = Bits.pageCount(length);
    long a = mappingAddress(offset);
    byte x = 0;
    try {
        for (int i=0; i<count; i++) {
            // TODO consider changing to getByteOpaque thus avoiding
            // dead code elimination and the need to calculate a checksum
            x ^= unsafe.getByte(a);
            a += ps;
        }
    } finally {
        Reference.reachabilityFence(this);
    }
    if (unused != 0)
        unused = x;

    return this;
}
 
Example 15
Source File: Test1.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
}
 
Example 16
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
}
 
Example 17
Source File: UnsafeRaw.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  Unsafe unsafe = Unsafe.getUnsafe();
  final int array_size = 128;
  final int element_size = 4;
  final int magic = 0x12345678;

  Random rnd = Utils.getRandomInstance();

  long array = unsafe.allocateMemory(array_size * element_size); // 128 ints
  long addr = array + array_size * element_size / 2; // something in the middle to work with
  unsafe.putInt(addr, magic);
  for (int j = 0; j < 100000; j++) {
     if (Tests.int_index(unsafe, addr, 0) != magic) throw new Exception();
     if (Tests.long_index(unsafe, addr, 0) != magic) throw new Exception();
     if (Tests.int_index_mul(unsafe, addr, 0) != magic) throw new Exception();
     if (Tests.long_index_mul(unsafe, addr, 0) != magic) throw new Exception();
     {
       long idx1 = rnd.nextLong();
       long addr1 = addr - (idx1 << 2);
       if (Tests.long_index(unsafe, addr1, idx1) != magic) throw new Exception();
     }
     {
       long idx2 = rnd.nextLong();
       long addr2 = addr - (idx2 >> 2);
       if (Tests.long_index_back_ashift(unsafe, addr2, idx2) != magic) throw new Exception();
     }
     {
       long idx3 = rnd.nextLong();
       long addr3 = addr - (idx3 >>> 2);
       if (Tests.long_index_back_lshift(unsafe, addr3, idx3) != magic) throw new Exception();
     }
     {
       long idx4 = 0x12345678;
       long addr4 = addr - idx4;
       if (Tests.int_const_12345678_index(unsafe, addr4) != magic) throw new Exception();
     }
     {
       long idx5 = 0x1234567890abcdefL;
       long addr5 = addr - idx5;
       if (Tests.long_const_1234567890abcdef_index(unsafe, addr5) != magic) throw new Exception();
     }
     {
       int idx6 = rnd.nextInt();
       long addr6 = addr - (idx6 >> 2);
       if (Tests.int_index_back_ashift(unsafe, addr6, idx6) != magic) throw new Exception();
     }
     {
       int idx7 = rnd.nextInt();
       long addr7 = addr - (idx7 >>> 2);
       if (Tests.int_index_back_lshift(unsafe, addr7, idx7) != magic) throw new Exception();
     }
     {
       int idx8 = rnd.nextInt();
       long addr8 = addr - (idx8 * 16);
       if (Tests.int_index_mul_scale_16(unsafe, addr8, idx8) != magic) throw new Exception();
     }
     {
       long idx9 = rnd.nextLong();
       long addr9 = addr - (idx9 * 16);
       if (Tests.long_index_mul_scale_16(unsafe, addr9, idx9) != magic) throw new Exception();
     }
  }
}
 
Example 18
Source File: Foo.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void run() {
    Unsafe unsafe = Unsafe.getUnsafe();
}
 
Example 19
Source File: RenderBuffer.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
protected RenderBuffer(int numBytes) {
    unsafe = Unsafe.getUnsafe();
    curAddress = baseAddress = unsafe.allocateMemory(numBytes);
    endAddress = baseAddress + numBytes;
    capacity = numBytes;
}
 
Example 20
Source File: RangeCheck.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();
    unsafe.getObject(new DummyClassWithMainRangeCheck(), Short.MAX_VALUE);
}