Assigning “null” to objects in every application a

2020-04-05 19:50发布

问题:

  • Do you always assign null to an object after its scope has been reached?

  • Or do you rely on the JVM for garbage collection?

  • Do you do it for all sort of applications regardless of their length?

  • If so, is it always a good practice?

回答1:

  • no, don't do that, except for specific cases such as static fields or when you know a variable/field lives a lot longer than the code referencing it
  • yes, but with a working knowledge of your VM's limits (and how to cause blocks of memory to be held accidentally)
  • n/a


回答2:

It's not necessary to explicitly mark objects as null unless you have a very specific reason. Furthermore, I've never seen an application that marks all objects as null when they are no longer needed. The main benefit of garbage collection is the intrinsic memory management.



回答3:

I declare almost all of my variables as "final". I also make my methods small and declare most variables local to methods.

Since they are final I cannot assign them null after use... but that is fine since the methods are small the objects are eligible for garbage collection once they return. Since most of the variables are local there is less chance of accidentally holding onto a reference for longer than needed (memory leak).



回答4:

Assignin null to a variable does not implicitly mean it will be garbage collected right away. In fact it most likely won't be. Whether you practice setting variables to null is usually only cosmetic (with the exception of static variables)



回答5:

We don't practice this assigning "null". If a variable's scope has reached it's end it should already be ready for GC. There may be some edge cases in which the scope lasts for a while longer due to a long running operation in which case it might make sense to set it to null, but I would imagine they would be rare.

It also goes without saying that if the variable is an object's member variable or a static variable and hence never really goes out of scope then setting it to null to GC is mandatory.



回答6:

Garbage collection is not as magical as you might expect. As long as an object is referenced from any reachable object it simply can't be collected. So it might be absolutely necessary to null a reference in order to avoid memory leaks. I don't say you should do this always, but always when it's necessary.



回答7:

As the others have mentioned, it's not usually necessary.

Not only that, but it clutters up your code and increases the data someone needs to read and understand when revisiting your code.



回答8:

Assigning is not done to objects, it is done to variables, and it means that this variable then holds a reference to some object. Assigning NULL to a variable is not a way to destroy an object, it just clears one reference. If the variable you are clearing will leave its scope afterwards anyway, assigning NULL is just useless noise, because that happens on leaving scope in any case.



回答9:

The one time I tend to use this practice is if I need to transform a large Collection in some early part of a method.

For example:

public void foo() {
  List<? extends Trade> trades = loadTrades();
  Map<Date, List<? extends Trade>> tradesByDate = groupTradesByDate(trades);
  trades = null; // trades no longer required.

  // Apply business logic to tradesByDate map.
}

Obviously I could reduce the need for this by refactoring this into another method: Map<Date, List<? extends Trade>>> loadTradesAndGroupByDate() so it really depends on circumstances / clarity of code.



回答10:

I only assign a reference to null when:

  1. The code really lies in a memory-critical part.
  2. The reference has a wide scope (and must be reused later). If it is not the case I just declare it in the smallest possible code block. It will be available for collection automatically.

That means that I only use this technique in iterative process where I use the reference to store incoming huge collection of objects. After processing, I do not need the collection any more but I want to reuse the reference for the next collection.

In that case (and only in that case), I then call System.gc() to give a hint to the Garbage Collector. I monitored this technique through heap visualizer and it works very well for big collections (more then 500Mb of data).



回答11:

When using the .Net I don't think there's a need to set the object to null. Just let the garbage collection happen.



回答12:

- Do you always assign null to an object after its scope has been reached?

No

- Or do you rely on the JVM for garbage collection?

Yes

- Do you do it for all sort of applications regardless of their length?

Yes

- If so, is it always a good practice?

N/A



回答13:

I assume you're asking this question because you've seen code with variables being assigned to null at the point where they will never be accessed again.

I dislike this style, but another programmer used it extensively, and said he was taught to do so at a programming course at his university. The reasoning he gave is that it would prevent undetectable bugs if he tried to reuse the variable later on, instead of indeterminate behavior, he'd get a null pointer exception.

So if you're prone to using variables where you shouldn't be using variables, it might make your code more easy to debug.



回答14:

There was a class of memory leak bugs that happened regardless of whether I set the reference to null - if the library I was using was written in a language like C without memory management, then simply setting the object to null would not necessarily free the memory. We had to call the object's close() method to release the memory (which, of course, we couldn't do after setting it to null.)

It thus seems to me that the de facto method of memory management in java is to rely on the garbage collector unless the object/library you're using has a close() method (or something similar.)