|
65 | 65 | import org.w3c.dom.Node; |
66 | 66 |
|
67 | 67 | import javax.annotation.Nullable; |
68 | | -import java.util.*; |
| 68 | +import java.lang.ref.WeakReference; |
| 69 | +import java.util.Arrays; |
| 70 | +import java.util.HashSet; |
| 71 | +import java.util.Iterator; |
| 72 | +import java.util.NoSuchElementException; |
| 73 | +import java.util.Set; |
69 | 74 |
|
70 | 75 | /** |
71 | 76 | * A fast node set implementation, based on arrays to store nodes and documents. |
|
91 | 96 | */ |
92 | 97 | public class NewArrayNodeSet extends AbstractArrayNodeSet implements ExtNodeSet, DocumentSet { |
93 | 98 |
|
94 | | - private Set<Collection> cachedCollections = null; |
| 99 | + @Nullable private WeakReference<Set<Collection>> cachedCollectionsRef = null; |
95 | 100 |
|
96 | 101 | private int documentCount = 0; |
97 | 102 |
|
@@ -1038,16 +1043,27 @@ public boolean equalDocs(final DocumentSet other) { |
1038 | 1043 |
|
1039 | 1044 | @Override |
1040 | 1045 | public Iterator<Collection> getCollectionIterator() { |
1041 | | - sort(); |
1042 | | - if(cachedCollections == null) { |
1043 | | - cachedCollections = new HashSet<>(); |
1044 | | - for(int i = 0; i < documentCount; i++) { |
1045 | | - final DocumentImpl doc = nodes[documentNodesOffset[i]].getOwnerDocument(); |
1046 | | - if(!cachedCollections.contains(doc.getCollection())) { |
1047 | | - cachedCollections.add(doc.getCollection()); |
1048 | | - } |
| 1046 | + // First, try and retrieve from Cache |
| 1047 | + Set<Collection> cachedCollections; |
| 1048 | + if (this.cachedCollectionsRef != null) { |
| 1049 | + cachedCollections = this.cachedCollectionsRef.get(); |
| 1050 | + if (cachedCollections != null) { |
| 1051 | + return cachedCollections.iterator(); |
1049 | 1052 | } |
1050 | 1053 | } |
| 1054 | + |
| 1055 | + sort(); |
| 1056 | + |
| 1057 | + // Second, Cache is empty, so create a Cache and return |
| 1058 | + cachedCollections = new HashSet<>(); |
| 1059 | + for (int i = 0; i < documentCount; i++) { |
| 1060 | + final DocumentImpl doc = nodes[documentNodesOffset[i]].getOwnerDocument(); |
| 1061 | + final Collection collection = doc.getCollection(); |
| 1062 | + cachedCollections.add(collection); |
| 1063 | + } |
| 1064 | + |
| 1065 | + this.cachedCollectionsRef = new WeakReference<>(cachedCollections); |
| 1066 | + |
1051 | 1067 | return cachedCollections.iterator(); |
1052 | 1068 | } |
1053 | 1069 |
|
|
0 commit comments