简体   繁体   中英

Free memory of a byte array in Java

释放由字节数组分配的内存的最佳方法是什么(Java中的新字节[size])?

停止引用它。

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.

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

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM