1

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()); } };

}

I don't understand why use the final keyword with WeakReference . Is there any benefit with the pattern.

Community
  • 1
  • 1
Fantasy_RQG
  • 143
  • 1
  • 13

1 Answers1

2

There's actually two different questions: why final should be used and why WeakReference should be used.

The final is used to indicate that the variable value will not ever change after construction. This documents the code (readers will readily know that it won't change), protects you from accidental change of this variable and may improve the runtime performance as JVM may use some additional optimizations for final fields.

The WeakReference is used in order not to unnecessarily prolong the lifetime of AutoCompleteTextView object: if it's discarded by its owner, then this observer should not hold it as well.

There's nothing especially strange in using both final modifier and WeakReference type together. Both of them serve their purpose.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • In my opinion,final will occupy memory and not release the memory out of the method field. used like this:
     
     public void setListener(final int position) {
            TextView mTextView = findViewById(R.id.my_text_view);
            mTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    data[postion].doSomething();
                }
            });
        }
    
    – Fantasy_RQG Jul 06 '15 at 08:05