DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Auditing Spring Boot Using JPA, Hibernate, and Spring Data JPA
  • How To Validate Archives and Identify Invalid Documents in Java
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Difference Between High-Level and Low-Level Programming Languages

Trending

  • OneStream Fast Data Extracts APIs
  • How To Use ChatGPT API in Python for Your Real-Time Data
  • What Is Kubernetes RBAC and Why Do You Need It?
  • Securing Your Applications With Spring Security
  1. DZone
  2. Coding
  3. Java
  4. Hacking the IntegerCache in Java 9?

Hacking the IntegerCache in Java 9?

Oh, hackable Java 8. Surely Java 9 will allow the same level of reflective access, right? Not so fast. Check out Java 9's failsafe's built in to protect the JVM.

Peter Verhas user avatar by
Peter Verhas
CORE ·
May. 04, 17 · Tutorial
Like (20)
Save
Tweet
Share
17.89K Views

Join the DZone community and get the full member experience.

Join For Free

Five years ago, I published an article in Hungarian about how to alter the IntegerCahe in the JDK. Doing that is essentially hacking the Java run-time, and there is no practical advantage unless, while you develop the hacking code, you get at better understanding how reflection works and how the Integer class is implemented.

The Integer class has a private nested class named IntegerCache that contains Integer objects for the int values -127 to 128. When the code has to box an int to Integer and the value is within this range, then the run-time uses the cache instead of creating a new Integer object. This is done for speed optimization reasons, bearing in mind that the int values in programs are, many times, in this range (think about array indexing).

The side effect of this is that many times, using the identity operator to compare two Integer objects may work so long as long the value is in the range. This is typically during unit testing. In operational mode, when some of the values get bigger than 128, the code fails.

Hacking the IntegerCache using reflection may also lead to mysterious side effects, and note that this is something that has its effect on the whole JVM. If a servlet redefines the small Integer cached values, then all other servlets running in the same Tomcat under the same JVM will suffer.

There are other articles about it on the net from Lukas Eder and on Sitepoint.

Now that I've started to play around with the Java 9 early access version, it came to my mind that I can do the same hacking with the new version of Java. Before starting that, let’s refresh what we did with Java 8.

Lukas, in his article, displays sample code that I'm copying here:

import java.lang.reflect.Field;
import java.util.Random;

public class Entropy {
    public static void main(String[] args)
    throws Exception {

        // Extract the IntegerCache through reflection
        Class << ? > clazz = Class.forName(
            "java.lang.Integer$IntegerCache");
        Field field = clazz.getDeclaredField("cache");
        field.setAccessible(true);
        Integer[] cache = (Integer[]) field.get(clazz);

        // Rewrite the Integer cache
        for (int i = 0; i < cache.length; i++) {
            cache[i] = new Integer(
                new Random().nextInt(cache.length));
        }

        // Prove randomness
        for (int i = 0; i < 10; i++) {
            System.out.println((Integer) i);
        }
    }
}


The code gets access to the IntegerCache via reflection and then fills the cache with random values. Naughty.

We can try to execute the same code in Java 9. Do not expect much fun though. Java 9 is more serious when somebody tries to violate it.

Exception in thread "main" java.lang.reflect.InaccessibleObjectException:
  Unable to make field static final java.lang.Integer[]
  java.lang.Integer$IntegerCache.cache
  accessible: module java.base does not "opens java.lang" to unnamed module @1bc6a36e


We get an exception that did not exist in Java 8. It says that the object is not accessible because the module java.base, which is the part of the run-time of the JDK that is automatically imported by each Java program, does not ‘opens’ (sic) the module to the unnamed module. It is thrown from the line where we try to set the field accessible.

The object we could easily access in Java 8 is not accessible anymore because the module system protects it. Code can only access fields, methods, and other things using reflection, only if the class is in the same module, or if the module opens the package for reflective access for the world or for the module that needs the access. This is done in the module-info.java module definition file:

module myModule {
    exports com.javax0.module.demo;
    opens com.javax0.module.demo;
}


The module java.base does not open itself for reflective access for us and especially not for the unnamed module, which is the code that we run. If we create a module for our code and name it, then the error message will contain the name of that module.

Can we open the module programmatic? There is an addOpens method in the java.lang.reflect.Module module.

Will it work?

Bad news for the hackers: It will not. It can only open a package in a module to another module if that package is already opened for the module calling this method. That way, modules can pass on to other modules the right that they already have to access some packages in a reflective way but can not open things that are not open.

But at the same time, this is good news. Java 9 is not so easily hackable, like Java 8 was. At least this little hole is closed. It seems that Java has started to be professional grade and not a toy. Soon the time will come when we can migrate serious programs from RPG and COBOL to Java. (Sorry for the joke.)

Java (programming language)

Published at DZone with permission of Peter Verhas, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Auditing Spring Boot Using JPA, Hibernate, and Spring Data JPA
  • How To Validate Archives and Identify Invalid Documents in Java
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Difference Between High-Level and Low-Level Programming Languages

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: