/
RemovableEntryIterator.java
71 lines (61 loc) · 1.97 KB
/
RemovableEntryIterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package org.infinispan.iteration.impl;
import org.infinispan.Cache;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.container.entries.CacheEntry;
import java.util.NoSuchElementException;
/**
* A CloseableIterator implementation that allows for a CloseableIterator that doesn't allow remove operations to
* implement remove by delegating the call to the provided cache to remove the previously read value.
*
* @author wburns
* @since 7.0
*/
public class RemovableEntryIterator<K, V, C> implements CloseableIterator<CacheEntry<K, C>> {
protected final CloseableIterator<CacheEntry<K, V>> realIterator;
protected final Cache<K, V> cache;
protected CacheEntry<K, C> previousValue;
protected CacheEntry<K, C> currentValue;
public RemovableEntryIterator(CloseableIterator<CacheEntry<K, V>> realIterator,
Cache<K, V> cache, boolean initIterator) {
this.realIterator = realIterator;
this.cache = cache;
if (initIterator) {
currentValue = getNextFromIterator();
}
}
protected CacheEntry<K, C> getNextFromIterator() {
if (realIterator.hasNext()) {
return (CacheEntry<K, C>) realIterator.next();
} else {
return null;
}
}
@Override
public boolean hasNext() {
return currentValue != null;
}
@Override
public CacheEntry<K, C> next() {
if (currentValue == null) {
throw new NoSuchElementException();
}
previousValue = currentValue;
// Set the current value to the next one if there is one
currentValue = getNextFromIterator();
return previousValue;
}
@Override
public void remove() {
if (previousValue == null) {
throw new IllegalStateException();
}
cache.remove(previousValue.getKey());
previousValue = null;
}
@Override
public void close() {
currentValue = null;
previousValue = null;
realIterator.close();
}
}