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?
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.