Exemplo n.º 1
0
  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");
  }