Tuesday, January 23, 2024

How to get negative number from size() in LinkedList in Java? ;-)

Yep, didn't wrote long time ;-)

Today will be "translation" of my post in Polish, but it is so fun that I decided to go with it ;-)

In short I wanted to break LinkedList in Java ;-)

I wanted to move LinkedList to state in which even when it was used in proper way it would stop to work for some stuff, or would return stupid answers. 

We will exploit "problem" in design of List in Java, its size is kept in int and may be up to Integer.MAX_VALUE. In case of implementations based on arrays this is quiet valid assumption. To be honest in case of computers used when Java Collections were created this was good assumption, but we are living 25 years into future so our computers are now 5-6k times faster, and have 5-8k times memory (In 1998 I had still 4 or 8 MB of RAM and was planning to upgrade to 64 MB of RAM, now I have in laptop which is 5 years old 32 GB of RAM ;-)).

So, idea is to have piece of code like:

var list = new LinkedList<Integer>();
doMagic(list);
System.out.println(list.size()); // return negative number!!!

Where doMagic looks like:

static void doMagic(LinkedList<Integer> l) {
for (var i=0L; i<Integer.MAX_VALUE+1000L; i++) {
l.add(Integer.valueOf(0));
}
}
So as we can see we are simply adding more than Integer.MAX_VALUE objects to our LinkedList.
By some time I wasn't able to run it on my machine because I was each time setting max heap size under 32 GB... and this would take 96-120 GB or so ;-) 
But it seems that you are able to setup Xmx to number bigger than your memory (at least on macOS) and after setting it to 150 GB I got 
-2147482649 from calling list.size(), and when I tried to execute:
var count = 0L;
for (var n:list) {
count++;
}

And I got also IndexOfOutBoundException with index 0 ;-) (it is because when iterator is created there is rangeCheck for 0, and when 0 is greater or equal to 0, it is still bigger than size of -2147482649 ;-)


Similar postsbeta
How many i 1+1 in Java? ;-)
Recursion is evil ;-)
Google Buzz - let's mark some comments as not spam ;-) or how to unhide "hidden" comments ;-)
Calculation of SSD life time in EEE PC
Portable code smells list ;-)

No comments:

Post a Comment