I am wondering how to instantiate a long[] array in Java with the greatest possible length. If it is too big, I get a memory error. I need this array to be as big as possible without exceeding the platform-dependent limit. How can this be done? The limit on my computer seems to be about 85000000 indices, but it may be less, or more, on other computers.
-
long has: class java.lang.Long : min = -9,223,372,036,854,775,808 , max = 9,223,372,036,854,775,807 – Vasyl Lyashkevych Jul 15 '17 at 02:10
-
2How could this possibly be of use? – Lev Kuznetsov Jul 15 '17 at 02:12
-
And you need this for...? – Abhijit Sarkar Jul 15 '17 at 02:33
-
I am programming a chess algorithm and this array will be a transposition table. The bigger the array is, the faster it runs. – Daniel Williams Jul 15 '17 at 02:54
-
Allocating all the available memory for yourself is dangerous. Remember that there are other things going on in a Java program besides just the app code that you wrote. Many of those things dynamically allocate memory, too, and will break if you've sucked it all up. You should look into a more flexible solution such as `WeakHashMap`. A `WeakHashMap` can grow large, but can also shrink in response to memory requirements from other things. – Kevin Anderson Jul 15 '17 at 03:45
2 Answers
In Java, garbage collection will be running in unpredictable interval. So free heap memory size will be increasing or decreasing depending on the runtime. So its highly unlikely that you can get the exact bytes of memory that you can use for making a long array, but you can try with Runtime class to get memory details used for JVM as:
Runtime.getRuntime().totalMemory()
,
Runtime.getRuntime().freeMemory()
,
Runtime.getRuntime().maxMemory()

- 96
- 2
-
Am I correct that Runtime.getRuntime().freeMemory()/8; should give me the approximate max length of the array? If so, it seems to give me a length of about 30 million, much less than the 85 million I would expect. – Daniel Williams Jul 15 '17 at 03:03
-
Yes, but its not the max that can be, because heap starts with size specified with -Xms switch and can grow upto size specified with -Xmx. freeMemory() only gives you free memory in current heap size. – Binayak Jul 15 '17 at 03:09
Indepent of the question, how to figure out, what the maximum usable space might be: If you really need only longs in that array you could also think of using java.nio.LongBuffer. Since you are working quite near at the machine, using this is quite similar to working in C with a C array but in a safe language.

- 3,333
- 2
- 15
- 29