Java中字节数组的空闲内存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2974251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:06:28  来源:igfitidea点击:

Free memory of a byte array in Java

javabytearraybyte

提问by fdezjose

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

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

回答by Alexander Pogrebnyak

Stop referencing it.

停止引用它。

回答by HoLyVieR

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

删除对该字节数组的所有引用。垃圾收集器会处理剩下的事情。

回答by Edwin Buck

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

在 Java 中创建新的 byte[] 时,您会执行类似的操作

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

您还需要将其他引用设置为 null,就像这样

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.

在 Java 中垃圾收集是自动的。如果 JVM 可以检测到整个程序无法再访问一块内存,那么 JVM 将为您释放内存。

回答by Alb

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();

将对其的所有引用设置为 null 将使其成为 Java 自动垃圾收集的候选对象。但是,您无法确定这需要多长时间才能发生。如果您确实需要立即显式回收内存,则可以调用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.

同样只是为了清除,您可能不需要显式地将引用设置为 null。如果引用超出范围,它们将被自动清空,例如,一旦在其声明的方法完成执行后,局部变量引用将被清空。所以局部变量通常在应用程序运行时一直隐式释放。