1 20 21 package org.snmp4j.agent.util; 22 23 import java.util.LinkedList ; 24 import java.util.Iterator ; 25 26 33 public class TemporaryList { 34 35 public static final int DEFAULT_ITEM_TIMEOUT = 5000; 36 37 private int timeout = DEFAULT_ITEM_TIMEOUT; 39 private LinkedList list = new LinkedList (); 40 41 public TemporaryList() { 42 } 43 44 public TemporaryList(int timeout) { 45 this.timeout = timeout; 46 } 47 48 public synchronized void add(Object o) { 49 long now = System.currentTimeMillis(); 50 if ((list.size() > 0) && 51 (((TemporaryListItem)list.getFirst()).atMaturity(now))) { 52 list.removeFirst(); 53 } 54 if ((list.size() > 0) && 55 (((TemporaryListItem)list.getLast()).atMaturity(now))) { 56 list.removeLast(); 57 } 58 list.addFirst(new TemporaryListItem(o)); 59 } 60 61 public synchronized boolean contains(Object o) { 62 for (Iterator it = list.iterator(); it.hasNext(); ) { 63 TemporaryListItem item = (TemporaryListItem) it.next(); 64 if (item.getItem().equals(o)) { 65 return true; 66 } 67 } 68 return false; 69 } 70 71 public synchronized boolean remove(Object o) { 72 long now = System.currentTimeMillis(); 73 for (Iterator it = list.iterator(); it.hasNext(); ) { 74 TemporaryListItem item = (TemporaryListItem)it.next(); 75 if (item.getItem().equals(o)) { 76 it.remove(); 77 return true; 78 } 79 else if (item.atMaturity(now)) { 80 it.remove(); 81 } 82 } 83 return false; 84 } 85 86 public void setTimeout(int timeout) { 87 this.timeout = timeout; 88 } 89 90 public int getTimeout() { 91 return timeout; 92 } 93 94 public Iterator iterator() { 95 return new TemporaryListIterator(); 96 } 97 98 public int size() { 99 return list.size(); 100 } 101 102 103 public synchronized void clear() { 104 list.clear(); 105 } 106 107 108 class TemporaryListItem { 109 private Object item; 110 private long timeOfMaturity; 111 112 public TemporaryListItem(Object item) { 113 this.item = item; 114 this.timeOfMaturity = System.currentTimeMillis() + timeout; 115 } 116 117 public long getTimeOfMaturity() { 118 return timeOfMaturity; 119 } 120 121 public Object getItem() { 122 return item; 123 } 124 125 public boolean equals(Object obj) { 126 return item.equals(obj); 127 } 128 129 public int hashCode() { 130 return item.hashCode(); 131 } 132 133 public boolean atMaturity(long referenceTime) { 134 return (referenceTime > timeOfMaturity); 135 } 136 } 137 138 class TemporaryListIterator implements Iterator { 139 140 private Iterator iterator; 141 142 public TemporaryListIterator() { 143 iterator = list.iterator(); 144 } 145 146 public boolean hasNext() { 147 return iterator.hasNext(); 148 } 149 150 public Object next() { 151 return ((TemporaryListItem)iterator.next()).getItem(); 152 } 153 154 public void remove() { 155 iterator.remove(); 156 } 157 158 } 159 } 160 | Popular Tags |