Free memory of a byte array in Java

2019-03-23 11:38发布

问题:

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

回答1:

Stop referencing it.



回答2:

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.



回答3:

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



回答4:

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.