First of all, the C function realloc
is not a tool that can grow arrays, but rather, memory previously allocated via malloc
, calloc
, or realloc
. In contrast, C arrays may reside on the stack or the static memory area and may even be embedded in a larger structure.
Then, the function has the semantics of invalidating the original pointer like free
does and returning a new pointer. So if you have copies of the pointer flying around, it’s your duty of replacing all occurrences with the new pointer.
Of course, Java does not support invalidating references. Guaranteeing the validity of every non-null
object reference, is the fundamental property of Java’s memory management.
So if you want the equivalent of C’s realloc
, you’d have to use pointers and not arrays. Then sun.misc.Unsafe
has all related operations
public long allocateMemory(long bytes)
public long reallocateMemory(long address, long bytes)
public void freeMemory(long address)
public float getXyz(long address)
¹
public void putXyz(long address, xyz x)
¹
¹ where “xyz” stands for a primitive type
If you want to resize an array, use
array = Arrays.copyOf(array, newSize);
this will not invalidate old references, so if you fail to replace all references to the old array, code using these old references will access the old array.
But if array
is the only reference to the particular array or your code provenly replaces all existing references, a JVM may in theory enable an in-place resizing operation instead of copying the contents, see also Does Java JIT cheat when running JDK code?
But checking the necessary preconditions might be more expensive than copying the array contents. The only scenario where I can imagine an applicability, would be if the array was the last object allocated by the same thread, so it could be proven that the reference did not escape yet and there’s no object behind the array within the allocation space.
For a JVM having such an optimization, you may get the benefit automatically when repeatedly adding to an ArrayList
, as that class ensures that it is the only holder of the reference to its internal array and it uses Arrays.copyOf
internally for resizing.