The misty “Unsafe” in Java

The Depths of “Unsafe” class in Java

KRISHNA KISHORE V
9 min readJun 22, 2022

--

Fig 1 Code for Getting Unsafe object

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:

  1. Accessing Hardware CPU feature — Compare And Swap
  2. Managing Native Memory
  3. Creating an object without running its constructor.
  4. Generate Classes at runtime.
  5. Faster Serialization
  6. Creating Arrays Bigger than the…

--

--

KRISHNA KISHORE V

Tech Lead | Full Stack Developer | Software Consultant | Technical Content Writer | Free Lancer