0

Until Java 8 it was possible to obtain the singleton sun.misc.Unsafe instance via a method like the following:

public static Unsafe getUnsafe() {
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Even though it was highly suggested not to use Unsafe, many vendors and libraries use it internally.

Now, with Java 9 and Jigsaw, I think that also the way Unsafe is handled has changed. I read some posts with contrary information. Some say it has been completely hidden and it is not even retrievable, others say one has to enable a VM flag, while others write that it should be officially support now.

So: Is it possible to still use sun.misc.Unsafe in Java 9, and if so, how?

Alan Bateman
  • 5,283
  • 1
  • 20
  • 25
Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
  • 1
    There is no such thing as `java.misc.Unsafe`. There is `sun.misc.Unsafe`, and it has been subject to the general `sun.*` package warning that has been present in every JDK release I have ever seen since 1997. – user207421 Nov 27 '17 at 09:26
  • 4
    sun.misc.Unsafe works the same on JDK 9 as it did on JDK 8. See JEP 260 for all the details. What issue are you running into? – Alan Bateman Nov 27 '17 at 09:26
  • 1
    The correct ending question should be, “and if so, *why*?”. – Holger Nov 27 '17 at 10:33

1 Answers1

5

Not only has it remained the same obtaining it, but they also added more methods to it. The thing is this is now a promise that it will be removed some time in the future; this time for sure.

Also there are two of them now, one : sun.misc.Unsafe and jdk.internal.misc.Unsafe. The first one is the one to be removed btw.

The second one can be obtained also in java-9, but only with the special key addExports:java.base/jdk.internal.misc=ALL-UNAMED (but this is highly discouraged).

What has changed is the fact that lots of public methods that were either patched or added so that you do not need to use it anymore, like AtomicInteger#weakCompareAndSet for example that was not doing what you would expect.

Eugene
  • 117,005
  • 15
  • 201
  • 306