Дата публикации: 04.11.2013 9:28:25
This article continues discussing my hash-based implementation of the caching mechanism. It describes supplementary classes needed to implement the Map interface. You can find the previous articles here and here.
Now the Cache class is fully functional and it completely implements the Map interface. In addition, I introduced several public methods that are useful sometimes. They are defined in the ConcurrentMap interface.
The Entries, Keys, and Values classes are needed to implement the entrySet(), keySet(), and values() methods respectively. These classes are implementations of the relevant collections with some restrictions described in the specification of the Map interface. The classes are similar to the inner classes of the same name, defined in the WeakHashMap class.
The AbstractIterator class is used by all three helper classes to create an iterator of the cache entries. Originally, it was created from the relevant inner class of the WeakHashMap class but then it was refactored. First, I added a strong reference to the keys as well as to the values. Second, I fixed the 8003417 bug, that I had found during testing the Cache class.
public boolean hasNext() { Entry<K,V>[] t = table; while (nextKey == null) { Entry<K,V> e = entry; int i = index; while (e == null && i > 0) e = t[--i]; entry = e; index = i; if (e == null) { currentKey = null; return false; } nextKey = e.get(); // hold on to key in strong ref if (nextKey == null) entry = entry.next; } return true; }
To fix the bug I deleted the code line that is marked in bold red in the above example. It works for my case. However, such solution is not applicable to fix a similar error in the WeakHashMap class.