Free memory of a byte array in Java

2019-03-23 11:56发布

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

4条回答
戒情不戒烟
2楼-- · 2019-03-23 12:19

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-03-23 12:31

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.

查看更多
等我变得足够好
4楼-- · 2019-03-23 12:31

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

查看更多
叛逆
5楼-- · 2019-03-23 12:37

Stop referencing it.

查看更多
登录 后发表回答