Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free memory of a byte array in Java

Tags:

What is the best way to release memory allocated by an array of bytes (new byte[size] in Java)?

like image 390
fdezjose Avatar asked Jun 04 '10 12:06

fdezjose


People also ask

How do you free up an array in Java?

yourArray = null; In Java garbage collection is automatic. If the JVM can detect that a piece of memory is no longer reachable by the entire program, then the JVM will free the memory for you. The JVM will free the memory when it feels like it.

How much memory is a byte in Java?

Byte Data Type A Java byte is the same size as a byte in computer memory: it's 8 bits, and can hold values ranging from -128 to 127.

How is memory freed in Java?

Java uses managed memory, so the only way you can allocate memory is by using the new operator, and the only way you can deallocate memory is by relying on the garbage collector.

How can you calculate the memory size of an array in Java?

According to the 64-bit memory model, an int is 4 bytes, so all the elements will be 4*N bytes in size. In addition to that, Java has a 24 bytes array overhead and there's also 8 bytes for the actual array object. So that's a total of 32 + 4 * N bytes. For a 2 dimensional array: int a[][] = new int[N][M];


2 Answers

Stop referencing it.

like image 151
Alexander Pogrebnyak Avatar answered Sep 28 '22 21:09

Alexander Pogrebnyak


When creating a new byte[] in Java, you do something like

byte[] myArray = new byte[54]; 

To free it, you should do

myArray = null; 

If something else references your byte array, like

yourArray = myArray; 

you need to also set the other references to null, like so

yourArray = null; 

In Java garbage collection is automatic. If the JVM can detect that a piece of memory is no longer reachable by the entire program, then the JVM will free the memory for you.

like image 28
Edwin Buck Avatar answered Sep 28 '22 21:09

Edwin Buck