The misty “Unsafe” in Java
The Depths of “Unsafe” class in Java
--
The Unsafe
class is the basis for implementing CAS in Java. In this article, we will understand more about Unsafe and its capabilities.
The name of the class Unsafe comes from the fact that it deals with. The sun.misc.Unsafe
is really meant to be a low-level VM library interface designed to be used strictly within the JDK. It is not intended for external use and was not part of the supported Java public interface.
Most of the concurrent collection classes and the fork-join framework in java.util.concurrency are written with the help of Unsafe
class. In fact, in Java 1.4, the reflections, serialization, and the NIO packages are re-written with Unsafe
to improve the performance. java.math.BigInteger
, java.math.BitDecimal
are also rewritten with Unsafe
in Java 7.
The
sun.misc.Unsafe
is really meant to be a low-level VM library interface designed to be used strictly in the JDK. It is not intended for external use.
Though the Unsafe
is not intended for use outside the JDK, there are the libraries that uses Unsafe
. But the real experts that know the low-level details can write better and safer programs with Unsafe
. And below are a few such projects.
Cassandra
Kafka
Zookeeper
LAMX Disruptor framework
Akka
Hibernate
Hadoop
HBase
Ehcache
Spring
Mockito and many more.
There is a lot of buzz around the Unsafe
class that from Java 9, it is gonna be deprecated or completely removed. If that is the case, what happens to the above projects if they have to be upgraded to later Java versions? Well, this is not only the case with Unsafe
, but also with all the internal APIs. But our concern is NOT to explore this now but just to understand what Unsafe
can do. For more information on this please look at the JEP-260 (JEP — JDK Enhancement Proposal).
The Unsafe
class is capable of doing many things, such as:
- Accessing Hardware CPU feature — Compare And Swap
- Managing Native Memory
- Creating an object without running its constructor.
- Generate Classes at runtime.
- Faster Serialization
- Creating Arrays Bigger than the…