为什么在WeakReference中使用final

时间:2015-06-27 04:27:43

标签: java memory-leaks weak-references

Example is here

 /**
     * Static inner listener that keeps a WeakReference to the actual AutoCompleteTextView.
     * 

* This way, if adapter has a longer life span than the View, we won't leak the View, instead * we will just leak a small Observer with 1 field. */ private static class PopupDataSetObserver extends DataSetObserver { private final WeakReference mViewReference; private PopupDataSetObserver(AutoCompleteTextView view) { mViewReference = new WeakReference(view); } @Override public void onChanged() { final AutoCompleteTextView textView = mViewReference.get(); if (textView != null && textView.mAdapter != null) { // If the popup is not showing already, showing it will cause // the list of data set observers attached to the adapter to // change. We can't do it from here, because we are in the middle // of iterating through the list of observers. textView.post(updateRunnable); } }

private final Runnable updateRunnable = new Runnable() { @Override public void run() { final AutoCompleteTextView textView = mViewReference.get(); if (textView == null) { return; } final ListAdapter adapter = textView.mAdapter; if (adapter == null) { return; } textView.updateDropDownForFilter(adapter.getCount()); } };

}

我不明白为什么在WeakReference中使用final关键字。该模式是否有任何好处。

1 个答案:

答案 0 :(得分:2)

实际上有两个不同的问题:为什么应该使用final以及为什么要使用WeakReference

final用于表示变量值在构造后不会改变。这记录了代码(读者很容易知道它不会发生变化),保护您免受此变量的意外更改,并可能提高运行时性能,因为JVM可能会对最终字段使用一些额外的优化。

使用WeakReference是为了不会不必要地延长AutoCompleteTextView对象的生命周期:如果它被所有者丢弃,那么这个观察者也不应该持有它。

在同时使用final修饰符和WeakReference类型时,没有什么特别奇怪的。它们都符合他们的目的。