0

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);
                          ^
mahmood
  • 23,197
  • 49
  • 147
  • 242
  • 1
    I suppose you should habe a sound understanding of Java BEFORE messing with the `Unsafe` class. (Hint: read on exception handling) – Gyro Gearless Apr 04 '14 at 11:10
  • yes some info on exception handling is required and what the different kinds of exception does java have and how you are supposed to use it in the code. clear case of not delcaring checked exceptions here. – vikeng21 Apr 04 '14 at 11:14

1 Answers1

3

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.

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
  • Try it. See if it works. Then read up on exceptions, and the [`ClassLoader#loadClass()'](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#loadClass(java.lang.String)) method. – Paul Hicks Apr 04 '14 at 11:10
  • The code in the link you posted includes this line: `public static void main(String[] args) throws Exception {`. It's pretty explicit: throw the Exceptions you're not handling. – Paul Hicks Apr 04 '14 at 11:19
  • Excuse me I mixed that with the top level class `Arr`. Thanks. – mahmood Apr 04 '14 at 11:26