Today in one of the code examples I saw this construction

private static final class ActionListener implements TextView.OnEditorActionListener { private final WeakReference<MainActivity> mainActivityWeakReference; public static ActionListener newInstance(MainActivity mainActivity) { WeakReference<MainActivity> mainActivityWeakReference = new WeakReference<>(mainActivity); return new ActionListener(mainActivityWeakReference); } private ActionListener(WeakReference<MainActivity> mainActivityWeakReference) { this.mainActivityWeakReference = mainActivityWeakReference; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { MainActivity mainActivity = mainActivityWeakReference.get(); if (mainActivity != null) { if (actionId == EditorInfo.IME_ACTION_GO && mainActivity.shouldShowError()) { mainActivity.showError(); } else { mainActivity.hideError(); } } return true; } } 

This is how it is applied.

 mEditText.setOnEditorActionListener(ActionListener.newInstance(this)); 

I don’t understand why to use weak links than it is better than the good old way to immediately pass the listener

 mBtnContinue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { doOnContinue(); } }); 

    2 answers 2

    I believe that the idea is as follows: in a specific project, a situation is possible in which:

    1. MainActivity not required on the screen, it does not need to show messages, and the corresponding object can be deleted
    2. However, mEditText is completely necessary and stores the listener.

    In this case, if the listener had kept the usual reference to MainActivity , then the garbage collector would not have the right to delete the corresponding object, which would lead to a memory leak: MainActivity not required, but for some reason it is stored. In the case of a weak link, just at the moment of removing the MainActivity listener from mEditText falls off.

    I must say that some leakage still happens - an object of the class ActionListener .

      Here, a weak link to activations is used for the situation when the developer (for some reason) decides to keep the link to ActionListener in an object that is not tied to the life cycle (for example, in some singleton). Then, if there is a normal link (not weak), there will be a memory leak. That is, the link to the activation will be stored in the application when the activation itself has already been destroyed.

      In this code, a weak link is used, which means the following: when crawling links, the GC will notice that there is only a weak link for activation, which means that the object can be deleted from memory (the activation object will be deleted from memory, even if we still store a link to ActionListener ).