0

Right now I am working on one java application. In that I am creating lots of method local objects. I am using WeakReference to create those objects in method like below.

public void method() {
    while(count < 10000000) {
       AnimalBean animal = new WeakReference<AnimalBean>(new AnimalBean()).get();
        //----------- HERE MY LOGIC -------------
    }
}

I have one doubts, Is it good idea to use WeakReference for local variables ? If NO then why ?

Thanks a lot in advance.

Dhiral Pandya
  • 10,311
  • 4
  • 47
  • 47
  • 1
    What would you gain by doing this? – JonK Oct 27 '15 at 15:54
  • I just want garbage collector to clean unnecessary object very quickly – Dhiral Pandya Oct 27 '15 at 15:56
  • Why? What's wrong with the way the collector currently collects garbage? – JonK Oct 27 '15 at 15:57
  • Thanks jonK for your quick comments, I just want to know Is it good idea, is it worth to create weak reference for local variable, Thanks again :) – Dhiral Pandya Oct 27 '15 at 15:59
  • No, it isn't. You're adding complexity unnecessarily, and you're creating even more objects doing it this way. The GC runs when it needs to, you don't need to help it along by creating weak references for local variables. – JonK Oct 27 '15 at 16:01
  • `animal` is allowed to be `null` in the way you've written the code. This is a deeply bad idea. – Louis Wasserman Oct 27 '15 at 17:10

1 Answers1

2

Here is the guide to Understand weak reference

You should think about using one whenever you need a reference to an object, but you don't want that reference to protect the object from the garbage collector. A classic example is a cache that you want to be garbage collected when memory usage gets too high (often implemented with WeakHashMap). Ref

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.

Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references. At the same time it will declare all of the formerly weakly-reachable objects to be finalizable. At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues.Ref

Community
  • 1
  • 1
Ami Patel
  • 296
  • 1
  • 13