fdezjose
fdezjose

Reputation: 259

Free memory of a byte array in Java

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

Upvotes: 25

Views: 77138

Answers (4)

Alb
Alb

Reputation: 3681

Setting all references to it to null will make it a candidate for Java's automatic garbage collection. You can't be sure how long it will take for this to happen though. If you really need to explicitly reclaim the memory immediately you can make a call to System.gc();

Also just to clear you may not need to set the references to null explicitly. If the references go out of scope they are automatically nulled e.g. a local variable reference will be nulled once the method it is declared in finishes executing. So local variables are usually released implicitly all the time during an apps runtime.

Upvotes: 3

Edwin Buck
Edwin Buck

Reputation: 70909

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.

Upvotes: 18

HoLyVieR
HoLyVieR

Reputation: 11134

Removing all the reference to that array of bytes. The garbage collector will take care of the rest.

Upvotes: 6

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

Stop referencing it.

Upvotes: 63

Related Questions