Java Code Examples for sun.misc.Unsafe#objectFieldOffset()

The following examples show how to use sun.misc.Unsafe#objectFieldOffset() . 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: UnsafeDemo.java    From smart-socket with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws NoSuchFieldException {
        Unsafe unsafe = getUnsafe();
        Student student = new Student("三刀", 18);
        Field nameField = Student.class.getDeclaredField("name");
        Field ageField = Student.class.getDeclaredField("age");

        long nameOffset = unsafe.objectFieldOffset(nameField);
        System.out.println("offset: " + nameOffset + " value: " + unsafe.getObject(student, nameOffset));

        long ageOffset = unsafe.objectFieldOffset(ageField);
        System.out.println("offset: " + ageOffset + " value: " + unsafe.getInt(student, ageOffset));

        unsafe.putObject(student, nameOffset, "sandao");
        System.out.println(student.getName());
//        unsafe.getInt()
    }
 
Example 2
Source File: ForkJoinWorkerThread.java    From a-foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new group with the system ThreadGroup (the
 * topmost, parent-less group) as parent.  Uses Unsafe to
 * traverse Thread.group and ThreadGroup.parent fields.
 */
private static ThreadGroup createThreadGroup() {
    try {
        final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
        f.setAccessible (true);
        Unsafe u = (Unsafe) f.get (null);
        Class<?> tk = Thread.class;
        Class<?> gk = ThreadGroup.class;
        long tg = u.objectFieldOffset(tk.getDeclaredField("group"));
        long gp = u.objectFieldOffset(gk.getDeclaredField("parent"));
        ThreadGroup group = (ThreadGroup)
            u.getObject(Thread.currentThread(), tg);
        while (group != null) {
            ThreadGroup parent = (ThreadGroup)u.getObject(group, gp);
            if (parent == null)
                return new ThreadGroup(group,
                                       "InnocuousForkJoinWorkerThreadGroup");
            group = parent;
        }
    } catch (Exception e) {
        throw new Error(e);
    }
    // fall through if null as cannot-happen safeguard
    throw new Error("Cannot create ThreadGroup");
}
 
Example 3
Source File: UnsafeIntegerFieldUpdater.java    From JobX with Apache License 2.0 5 votes vote down vote up
UnsafeIntegerFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 4
Source File: UnsafeAtomicLongFieldUpdater.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
UnsafeAtomicLongFieldUpdater(Unsafe unsafe, Class<?> tClass, String fieldName) throws NoSuchFieldException {
    Field field = tClass.getDeclaredField(fieldName);
    if (!Modifier.isVolatile(field.getModifiers())) {
        throw new IllegalArgumentException("Must be volatile");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 5
Source File: UnsafeAtomicIntegerFieldUpdater.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
UnsafeAtomicIntegerFieldUpdater(Unsafe unsafe, Class<?> tClass, String fieldName) throws NoSuchFieldException {
    Field field = tClass.getDeclaredField(fieldName);
    if (!Modifier.isVolatile(field.getModifiers())) {
        throw new IllegalArgumentException("Must be volatile");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 6
Source File: UnsafeAtomicReferenceFieldUpdater.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
UnsafeAtomicReferenceFieldUpdater(Unsafe unsafe, Class<U> tClass, String fieldName) throws NoSuchFieldException {
    Field field = tClass.getDeclaredField(fieldName);
    if (!Modifier.isVolatile(field.getModifiers())) {
        throw new IllegalArgumentException("Must be volatile");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 7
Source File: UnsafeIntegerFieldUpdater.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
UnsafeIntegerFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    final Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 8
Source File: UnsafeReferenceFieldUpdater.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
UnsafeReferenceFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    final Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 9
Source File: UnsafeLongFieldUpdater.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
UnsafeLongFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    final Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    this.offset = unsafe.objectFieldOffset(field);
}
 
Example 10
Source File: UnsafeAtomicReferenceFieldUpdater.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
UnsafeAtomicReferenceFieldUpdater(Unsafe unsafe, Class<U> tClass, String fieldName) throws NoSuchFieldException {
    Field field = tClass.getDeclaredField(fieldName);
    if (!Modifier.isVolatile(field.getModifiers())) {
        throw new IllegalArgumentException("Field [" + fieldName + "] must be volatile");
    }
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 11
Source File: UnsafeAtomicReferenceFieldUpdater.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
UnsafeAtomicReferenceFieldUpdater(Unsafe unsafe, Class<U> tClass, String fieldName) throws NoSuchFieldException {
  Field field = tClass.getDeclaredField(fieldName);
  if (!Modifier.isVolatile(field.getModifiers())) {
    throw new IllegalArgumentException("Must be volatile");
  }
  this.unsafe = unsafe;
  offset = unsafe.objectFieldOffset(field);
}
 
Example 12
Source File: AccessibleObject_layout.java    From manifold with Apache License 2.0 5 votes vote down vote up
static long getOverrideOffset( Unsafe unsafe )
{
  try
  {
    return unsafe.objectFieldOffset( AccessibleObject_layout.class.getDeclaredField( "override" ) );
  }
  catch( NoSuchFieldException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 13
Source File: UnsafeLongFieldUpdater.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
UnsafeLongFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    final Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    this.offset = unsafe.objectFieldOffset(field);
}
 
Example 14
Source File: ClassLoaderUtils.java    From arthas with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "restriction", "unchecked" })
public static URL[] getUrls(ClassLoader classLoader) {
    if (classLoader instanceof URLClassLoader) {
        return ((URLClassLoader) classLoader).getURLs();
    }

    // jdk9
    if (classLoader.getClass().getName().startsWith("jdk.internal.loader.ClassLoaders$")) {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            Unsafe unsafe = (Unsafe) field.get(null);

            // jdk.internal.loader.ClassLoaders.AppClassLoader.ucp
            Field ucpField = classLoader.getClass().getDeclaredField("ucp");
            long ucpFieldOffset = unsafe.objectFieldOffset(ucpField);
            Object ucpObject = unsafe.getObject(classLoader, ucpFieldOffset);

            // jdk.internal.loader.URLClassPath.path
            Field pathField = ucpField.getType().getDeclaredField("path");
            long pathFieldOffset = unsafe.objectFieldOffset(pathField);
            ArrayList<URL> path = (ArrayList<URL>) unsafe.getObject(ucpObject, pathFieldOffset);

            return path.toArray(new URL[path.size()]);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return null;
}
 
Example 15
Source File: JacocoCoverageRunner.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static URL[] getUrls(ClassLoader classLoader) {
  if (classLoader instanceof URLClassLoader) {
    return ((URLClassLoader) classLoader).getURLs();
  }

  // java 9 and later
  if (classLoader.getClass().getName().startsWith("jdk.internal.loader.ClassLoaders$")) {
    try {
      Field field = Unsafe.class.getDeclaredField("theUnsafe");
      field.setAccessible(true);
      Unsafe unsafe = (Unsafe) field.get(null);

      // jdk.internal.loader.ClassLoaders.AppClassLoader.ucp
      Field ucpField = classLoader.getClass().getDeclaredField("ucp");
      long ucpFieldOffset = unsafe.objectFieldOffset(ucpField);
      Object ucpObject = unsafe.getObject(classLoader, ucpFieldOffset);

      // jdk.internal.loader.URLClassPath.path
      Field pathField = ucpField.getType().getDeclaredField("path");
      long pathFieldOffset = unsafe.objectFieldOffset(pathField);
      ArrayList<URL> path = (ArrayList<URL>) unsafe.getObject(ucpObject, pathFieldOffset);

      return path.toArray(new URL[path.size()]);
    } catch (Exception e) {
      return null;
    }
  }
  return null;
}
 
Example 16
Source File: TestSolutionDefaultConstructorInvocation.java    From java-katas with MIT License 5 votes vote down vote up
@Test
@Tag("PASSING")
@Order(2)
public void unsafeNoParamConstructor() {

    String expectedOutput = "[I am Unsafe.] - Default constructor via Unsafe";

    try {

        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        final Unsafe unsafe = (Unsafe) theUnsafeInstance.get(null);

        // Allocate instance does not go through initialization process, no constructor called.
        DemoClass demoClass = (DemoClass)
                unsafe.allocateInstance(DemoClass.class);

        // Get a handle to the "name" field of DemoClass
        Field nameFieldOfDemoClass = DemoClass.class.getDeclaredField("name");

        // Determine the memory offset location of the field in any instance of DemoClass.
        final long offset = unsafe.objectFieldOffset(nameFieldOfDemoClass);

        // Get the field for the DemoClass instance created above & set its value.
        unsafe.getAndSetObject(demoClass, offset, "I am Unsafe.");

        assertEquals(expectedOutput,
                demoClass.printStuff("Default constructor via Unsafe"),
                "Unsafe invocation failed");

    } catch (InstantiationException | IllegalAccessException | NoSuchFieldException e) {

        fail(UNSAFE_FAILURE.getValue() + e.getMessage());
    }
}
 
Example 17
Source File: UnsafeIntegerFieldUpdater.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
UnsafeIntegerFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    final Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    this.offset = unsafe.objectFieldOffset(field);
}
 
Example 18
Source File: UnsafeReferenceFieldUpdater.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
UnsafeReferenceFieldUpdater(Unsafe unsafe, Class<? super U> tClass, String fieldName) throws NoSuchFieldException {
    final Field field = tClass.getDeclaredField(fieldName);
    if (unsafe == null) {
        throw new NullPointerException("unsafe");
    }
    this.unsafe = unsafe;
    this.offset = unsafe.objectFieldOffset(field);
}
 
Example 19
Source File: TestKataCompareAndSet.java    From java-katas with MIT License 4 votes vote down vote up
@Test
@Tag("PASSING")
@Order(3)
public void compareAndSetUsingUnsafe() {

    try {

        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        final Unsafe unsafe = (Unsafe) theUnsafeInstance.get(null);

        final long offset;

        offset = unsafe.objectFieldOffset(
                TestKataCompareAndSet.class.getDeclaredField("privateVolatile"));

        boolean exchanged = unsafe.compareAndSwapObject(this,
                offset, currentValue, newValue);

        assertTrue(exchanged,
                "The value should have been changed to 7, " +
                        "hence exchanged should be true"
                );

        assertEquals(newValue,
                unsafe.getObject(this, offset),
                "The value of the privateVolatile should now be 7");

        exchanged = unsafe.compareAndSwapObject(this, offset, 2, 33);

        assertFalse(exchanged,
                "The value should not have changed since the expected value " +
                        "did not match, hence exchanged should be false"
                );

        assertEquals(newValue,
                unsafe.getObject(this, offset),
                "The value of the privateVolatile should still be 7");

    } catch (NoSuchFieldException | IllegalAccessException e) {

        fail(UNSAFE_FAILURE.getValue() + e.getMessage());

    }

}
 
Example 20
Source File: TestSolutionCompareAndSet.java    From java-katas with MIT License 4 votes vote down vote up
@Test
@Tag("PASSING")
@Order(3)
public void compareAndSetUsingUnsafe() {

    try {

        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        final Unsafe unsafe = (Unsafe) theUnsafeInstance.get(null);

        final long offset;

        offset = unsafe.objectFieldOffset(
                TestSolutionCompareAndSet.class.getDeclaredField("privateVolatile"));

        boolean exchanged = unsafe.compareAndSwapObject(this,
                offset, currentValue, newValue);

        assertTrue(exchanged,
                "The value should have been changed to 7, " +
                        "hence exchanged should be true"
                );

        assertEquals(newValue,
                unsafe.getObject(this, offset),
                "The value of the privateVolatile should now be 7");

        exchanged = unsafe.compareAndSwapObject(this, offset, 2, 33);

        assertFalse(exchanged,
                "The value should not have changed since the expected value " +
                        "did not match, hence exchanged should be false"
                );

        assertEquals(newValue,
                unsafe.getObject(this, offset),
                "The value of the privateVolatile should still be 7");

    } catch (NoSuchFieldException | IllegalAccessException e) {

        fail(UNSAFE_FAILURE.getValue() + e.getMessage());

    }

}