Unsafe and JPMS

Jeremy Manson jeremymanson at google.com
Fri Jan 19 01:28:47 UTC 2018

Hey folks,

I know this has come up before, but I wanted to revive the question.  As we
play more and more with JPMS and Java 9, we're finding more and more places
where Unsafe is now the only feasible way to achieve what we want to

The big use case is, of course, access to the internals of modularized
libraries in ways that would have used standard reflection in Java 8 and
earlier, but for which we now fail with an exception.

The answer of adding command line flags doesn't really work for general
purpose libraries.  If I want to do this in (for example) Guava, asking
every Guava user to add add-opens on the command line is a complete
non-starter.  Many people have no idea what libraries they are using.

The answer of creating an agent is also a non-starter for similar reasons.

The answer of using privateLookupIn assumes that you have access to or
control over the target class, which is often not the case, especially if
you are introspecting into JDK internals.

As people within Google try Java 9, this is coming up in quite a bit of our
infrastructure, especially in diagnostic code.  The latest place I've found
it was a tool that printed out / counted the number of objects reachable
from a root object; it died when it got into a JDK library.  I've noticed
quite a few people using Unsafe as a workaround in OSS libraries, too: Netty
<https://github.com/netty/netty/issues/6269>, Kryo
<https://github.com/EsotericSoftware/kryo/issues/543>, cglib

So... OpenJDK has this commitment not to replace Unsafe without providing
supported replacements for its functionality and a transition period.  Does
that include the functionality that Unsafe can break module encapsulation?



More information about the core-libs-dev mailing list