Using Java's ReferenceQueue

前端 未结 4 1604
轮回少年
轮回少年 2020-12-01 00:23

Do SoftReference and WeakReference really only help when created as instance variables? Is there any benefit to using them in method scope?

4条回答
  •  孤独总比滥情好
    2020-12-01 01:01

    One common idiom with reference queues is to e.g. subclass WeakReference to attach information that's needed to clean up things, and then to poll a ReferenceQueue to get cleanup tasks.

    ReferenceQueue fooQueue = new ReferenceQueue();
    
    class ReferenceWithCleanup extends WeakReference {
      Bar bar;
      ReferenceWithCleanup(Foo foo, Bar bar) {
        super(foo, fooQueue);
        this.bar = bar;
      }
      public void cleanUp() {
        bar.cleanUp();
      }
    }
    
    public Thread cleanupThread = new Thread() {
      public void run() {
        while(true) {
          ReferenceWithCleanup ref = (ReferenceWithCleanup)fooQueue.remove();
          ref.cleanUp();
        }
      }
    }
    
    public void doStuff() {
      cleanupThread.start();
      Foo foo = new Foo();
      Bar bar = new Bar();
      ReferenceWithCleanup ref = new ReferenceWithCleanup(foo, bar);
      ... // From now on, once you release all non-weak references to foo,
          // then at some indeterminate point in the future, bar.cleanUp() will
          // be run. You can force it by calling ref.enqueue().
    }
    

    For example, the internals of Guava's CacheBuilder implementation when weakKeys are selected uses this approach.

提交回复
热议问题