1 19 package org.objectweb.carol.cmi; 20 21 import java.lang.ref.WeakReference ; 22 import java.util.Iterator ; 23 import java.util.NoSuchElementException ; 24 25 31 public class WeakList { 32 private final Object listHead = new Object (); 33 private WeakLink listStart; 34 35 private static class WeakLink extends WeakReference { 36 public WeakLink next; 37 public WeakLink prev; 38 WeakLink(Object o) { 39 super(o); 40 } 41 } 42 43 public WeakList() { 44 listStart = new WeakLink(listHead); 45 listStart.next = listStart; 46 listStart.prev = listStart; 47 } 48 49 public void put(Object o) { 50 WeakLink n = new WeakLink(o); 51 synchronized (listHead) { 52 WeakLink prev = listStart; 53 WeakLink next = listStart.next; 54 n.prev = prev; 55 n.next = next; 56 prev.next = n; 57 next.prev = n; 58 } 59 } 60 61 private class ListIterator implements Iterator { 62 private WeakLink link = listStart; 63 private Object obj; 64 private boolean isNext = false; 65 66 public ListIterator() { 67 } 69 70 private void pinNext() { 71 WeakLink l = link.next; 72 Object o = l.get(); 73 if (o == null) { 74 synchronized (listHead) { 76 l = link; 77 do { 78 l = l.next; 79 o = l.get(); 80 } while (o == null); 81 link.next = l; 82 l.prev = link; 83 } 84 } 85 link = l; 86 obj = o; 87 isNext = true; 88 } 89 90 public boolean hasNext() { 91 if (!isNext) { 92 pinNext(); 93 } 94 return obj != listHead; 95 } 96 97 public Object next() { 98 if (!isNext) { 99 pinNext(); 100 } 101 if (obj == listHead) { 102 throw new NoSuchElementException (); 103 } 104 isNext = false; 105 return obj; 106 } 107 108 public void remove() { 109 throw new UnsupportedOperationException (); 110 } 111 } 112 113 public Iterator iterator() { 114 return new ListIterator(); 115 } 116 } 117 | Popular Tags |