Java proposal would scrap sun.misc.Unsafe memory access

Memory access methods in the 20-year-old class for performing low-level operations would be marked for removal in a future Java release.

Garbage can paper trash
Thinkstock

The memory access methods of Java’s sun.misc.Unsafe class would be deprecated for removal in a future release of the platform, under a JEP (JDK Enhancement Proposal) afoot in the OpenJDK community. Of the class’s 87 methods, 79 would be removed.

These unsupported methods have had supported replacements since JDK 9, for accessing on-heap memory, and JDK 22, for accessing off-heap memory, the proposal states. Library developers are strongly encouraged to migrate from sun.misc.Unsafe to these supported replacements. Goals of the proposal include preparing for the removal of these memory access methods in a future Java release and helping developers know when their applications rely on them. It is not a goal of the proposal to remove the sun.misc.Unsafe class entirely, as a small number of its methods are not used for memory access and will remain undeprecated. 

The proposal does not cite a specific release of Java that would deprecate the methods. The next version of standard Java, JDK 22, due in March, already has its feature set frozen. But JDK 23, likely to be released in September, could be a possible target. 

In the past, unsafe code was viewed as required for low-level programming. The sun.misc.Unsafe class was introduced in 2002 as a way for Java classes in the JDK to perform low-level operations. Its memory access methods, as the name of the class suggests, are unsafe and can lead to undefined behavior, so they were not exposed as a standard API. They were introduced with the assumption that they were exclusively for use within the JDK, that callers within the JDK would perform exhaustive safety checks before using them, and that safe standard APIs for the functionality would be added to the Java platform, the proposal says. 

But with no way in 2002 to prevent sun.misc.Unsafe from being used outside the JDK, its memory access methods became a “Swiss Army knife” for library developers who wanted more power and performance than standard APIs could provide. Unfortunately, not all libraries perform safety checks before calling these methods, thus presenting a risk of failures and crashes in applications.

During the past several years, two standard APIs have been introduced as replacements for the memory access methods in sun.misc.Unsafe. These are java.lang.invoke from JDK 9 and java.lang.foreign from JDK 22.

Copyright © 2024 IDG Communications, Inc.