문제

I have wrote a simple code to use Unsafe.prefetchRead on an array and used this test code as a template.

import sun.misc.Unsafe;
import java.lang.reflect.*;
public class Arr {
  static int [] a = new int[3];
  static Unsafe unsafe;
  static int baseOffset, indexScale;
  public static void main(String[] args)  {
    a[0] = 10;    a[1] = 20;    a[2] = 30;

    Class c = Arr.class.getClassLoader().loadClass("sun.misc.Unsafe");
    Field f = c.getDeclaredField("theUnsafe");
    f.setAccessible(true);
    unsafe = (Unsafe)f.get(c);

    baseOffset = unsafe.arrayBaseOffset(int[].class);
    indexScale = unsafe.arrayIndexScale(int[].class);
    for (int i = 0; i < 3; i++)  {
      unsafe.prefetchReadStatic(a, baseOffset+indexScale*i);
      System.out.println(a[i]);
    }
  }
}

However I get these errors

Arr.java:14: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
    Class c = Arr.class.getClassLoader().loadClass("sun.misc.Unsafe");
                                                  ^
Arr.java:15: unreported exception java.lang.NoSuchFieldException; must be caught or declared to be thrown
    Field f = c.getDeclaredField("theUnsafe");
                                ^
Arr.java:17: unreported exception java.lang.IllegalAccessException; must be caught or declared to be thrown
    unsafe = (Unsafe)f.get(c);
                          ^
도움이 되었습니까?

해결책

To get it working, change public static void main(String[] args) { to public static void main(String[] args) throws Exception {.

Then read up on exceptions. The ClassLoader#loadClass(String) method throws the declared exception ClassNotFoundException. You must handle it, or allow it to be thrown out of your method. Same for the other two errors.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top