コード例 #1
0
ファイル: AllocateMemory.java プロジェクト: netroby/jdk9-dev
  public static void main(String args[]) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();

    // Allocate a byte, write to the location and read back the value
    long address = unsafe.allocateMemory(1);
    assertNotEquals(address, 0L);

    unsafe.putByte(address, Byte.MAX_VALUE);
    assertEquals(Byte.MAX_VALUE, unsafe.getByte(address));
    unsafe.freeMemory(address);

    // Call to allocateMemory() with a negative value should result in an IllegalArgumentException
    try {
      address = unsafe.allocateMemory(-1);
      throw new RuntimeException("Did not get expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // Expected
      assertNotEquals(address, 0L);
    }

    // allocateMemory() should throw an OutOfMemoryError when the underlying malloc fails,
    // we test this by limiting the malloc using -XX:MallocMaxTestWords
    try {
      address = unsafe.allocateMemory(100 * 1024 * 1024 * 8);
    } catch (OutOfMemoryError e) {
      // Expected
      return;
    }
    throw new RuntimeException("Did not get expected OutOfMemoryError");
  }
コード例 #2
0
ファイル: GetPutFloat.java プロジェクト: netroby/jdk9-dev
  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;
    }
  }