Java – explicit zeroing

Under what circumstances, Java is explicit and nulling is useful Does it help the garbage collector in any way by making objects unreachable or in some way? Is it considered a good practice?

Solution

In Java, if you have a very long method and the only reference to the object is through local variables, it can help you Setting the local variable to null when you no longer need it (but when the method will continue to run for a long time) can help GC (in C #, this is very useful because GC needs to consider the "last possible use". This optimization may keep Java for a while - I don't know.)

Similarly, if you have a member field that references an object and you no longer need it, you can help GC by setting the field to null

However, in my experience, doing one of these things is rarely useful. It makes the code simpler Few methods actually run for a long time and setting the variable to null is independent of the method implementation you want It's not a good practice when you don't need it, if you need it, you should see whether refactoring can improve your design first (you may have too many methods or types.)

Note that setting the variable to null is completely passive – it does not notify the garbage collector that the object can be collected, it just prevents the garbage collector from seeing the reference run as the reason (GC) for the next retention of the object

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>