title: Java 8 lambda weak reference
body: <p>I create an object called <code>Foo</code>. When I create a lambda or method reference called <code>Action</code>, the <code>Action</code> object holds a reference to <code>Foo</code>.<br>
  I pass the action to another class. But if I hold it as a weak reference, it gets gc immediately, because no one stores another reference to <code>Action</code>.<br>
  But if i hold it as a strong reference, the <code>Foo</code> can't be gc, because <code>Action</code> holds a referene to it.<br>
  So memory leaks happen and I want to prevent it.</p>
  
  <p>My question is: how can I hold a reference to <code>Action</code> without preventing gc of <code>Foo</code>.</p>
  
  <p>Example:</p>
  
  <pre><code>Interface Action {
      void invoke();
  }
  
  Class Foo() {
      public void someMethod() {
          ....
      }
  }
  
  Class Holder() {
       WeakRefrence&lt;Object&gt; foo;
       public Action action;
  
       void register(Object source, Action a) {
           foo = new WeakReference(source);
           ??? how can i hold the action without prevent source to gc able.
       }
  }
  
  
  main() {
      Holder holder = new Holder();
      Foo foo = new Foo();
      Action action = foo::someMethod;
  
      holder.register(foo,action);
      action = null;
      System.gc();
      //only the holder store reference to action.
      //if i store in holder as weak reference i cannot invoke it any more cause it get gc.
  
      //foo = null;
      //System.gc();
      //if i grab action in holder as strong refrence the foo cant be gc cause action hold refernce to it.
  
      holder.action.invoke();
  }
  </code></pre>