Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling Java Integer Cache

Tags:

java

Recently stumbled on a problem related to the Java Integer Cache and I'm looking for a way to disable it.

Right now testing is impossible because we can't say it works unless we test with an integer value outside of the cache.

Our case : We had 8 buggy != comparisons and everything worked fine during 2 months of testing because we never had an underlying database entity with a PK higher than 128.

like image 915
ForguesR Avatar asked Mar 06 '23 12:03

ForguesR


2 Answers

You don't. The integer cache is an implementation detail of Integer. If you use Integer, you accept the cache. It's a good thing, there to reduce the number of effectively duplicate objects which may be created.

Use FindBugs to locate spurious integer reference comparisons and replace them with Integer.equals -- that is the proper way to fix the problems you're encountering.

If problems which are this fundamental to the language are present in your application then I strongly suggest running a full suite of static analysis tests and working your way through to triage them.

like image 115
Michael Avatar answered Mar 19 '23 22:03

Michael


The simplest thing to do to address and catch this kind of bug is to write a unit test that has a primary key arbitrarily (and randomly) higher than 128.

This gives you:

  • An Integer out of the IntegerCache
  • A way to independently validate this without having to change any runtime parameters (i.e. easily repeatable on developer boxes)
  • Concise documentation in the form of tests that states that you want to be sure that these values are actually being accounted for

You do not need to disable JVM internals to test this. You just need to be aware of their limitations and test around them if their case poses a challenge for your application.

like image 20
Makoto Avatar answered Mar 19 '23 21:03

Makoto