Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: implementation of notification provider vs. hashCode-driven Map
    text
    copied!<p>I have implemented abstract generic provider for notification bunch of generic listeners <code>E</code>, descendants have to override <code>notifyListener(E)</code> with specific notification code. For backing list of listeners I choose <code>WeakHashMap&lt;K,V&gt;</code>. Listeners must be held as weak references:</p> <pre><code>abstract public class NotificationProvider&lt;E&gt; { private Map&lt;E, Object&gt; listeners = new WeakHashMap&lt;E, Object&gt;(); public addListener(E listener) { listeners.put(listener, null); } public void notifyListeners() { for (E listener: listeners.keySet()) notifyListener(listener); } abstract protected void notifyListener(E listener); } </code></pre> <p>Typical use:</p> <pre><code> NotificationProvider&lt;MyListener&gt; provider; provider = new NotificationProvider&lt;MyListener&gt;() { @Override protected void notifyListener(MyListener listener) { listener.myNotification(); } } provider.addListener(myListener1); provider.addListener(myListener2); provider.notifyListeners(); </code></pre> <p>Everything works well, but when I need <code>AbstractList</code> descendant class as listener, backing <code>WeakHashMap</code> accepts only one listener instance! It's clear -- methods <code>hashCode()</code> and <code>equals()</code> on listeners return same value for all of instances (empty lists), so <code>WeakHashMap.put</code> only replace previously added listener.</p> <pre><code> public class MyList extends AbstractList&lt;MyItem&gt; { // some implementation } NotificationProvider&lt;MyList&gt; provider; provider = new NotificationProvider&lt;MyList&gt;() { @Override protected void notifyListener(MyList listener) { // some implementation } } MyList list1 = new MyList(); MyList list2 = new MyList(); provider.addListener(list1); provider.addListener(list2); provider.notifyListeners(); // only list2 instance is notified </code></pre> <p>What is the best solution?</p> <ol> <li><p>use another non-hashCode backing collection -- but <code>WeakHashMap</code> is so sweet for me, because automatically managing weak references for me</p></li> <li><p>use non-generic listener, for example abstract class with simple <code>equals() { return (this == object); }</code> implementation -- but this is not so flexible</p></li> <li><p>use some wrapper for listeners with simple equals() -- but this wrapper cannot be transparent to <code>addListener(E)</code> caller due to weak references</p></li> </ol> <p>Another ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload