1 5 package com.tc.util; 6 7 import java.util.AbstractSet ; 8 import java.util.Collection ; 9 import java.util.Iterator ; 10 import java.util.Set ; 11 12 public class SyncObjectIdSetImpl extends AbstractSet implements SyncObjectIdSet { 13 14 private final Object lock = new Object (); 15 private ObjectIDSet2 set = new ObjectIDSet2(); 16 private boolean isBlocking = false; 17 18 public void startPopulating() { 19 synchronized (lock) { 20 isBlocking = true; 21 } 22 } 23 24 public void stopPopulating(ObjectIDSet2 fullSet) { 25 synchronized (lock) { 26 isBlocking = false; 27 ObjectIDSet2 large = (fullSet.size() > set.size()) ? fullSet : set; 28 ObjectIDSet2 small = (set == large) ? fullSet : set; 29 large.addAll(small); 30 set = large; 31 lock.notifyAll(); 32 } 33 } 34 35 public boolean add(Object obj) { 36 synchronized (lock) { 37 return set.add(obj); 38 } 39 } 40 41 public void addAll(Set s) { 42 synchronized (lock) { 43 set.addAll(s); 44 } 45 } 46 47 public boolean contains(Object o) { 48 boolean rv = false; 49 synchronized(lock) { 50 rv = set.contains(o); 51 if (isBlocking && !rv) { 52 waitOn(lock); 53 rv = set.contains(o); 54 } 55 } 56 return rv; 57 } 58 59 public boolean removeAll(Collection ids) { 60 boolean rv = false; 61 synchronized (lock) { 62 if (isBlocking) waitOn(lock); 63 rv = set.removeAll(ids); 64 } 65 return rv; 66 } 67 68 public boolean remove(Object o) { 69 boolean rv = false; 70 synchronized (lock) { 71 if(isBlocking) waitOn(lock); 72 rv = set.remove(o); 73 } 74 return rv; 75 } 76 77 public Iterator iterator() { 78 Iterator rv = null; 79 synchronized (lock) { 80 if (isBlocking) waitOn(lock); 81 rv = set.iterator(); 82 } 83 return rv; 84 } 85 86 public int size() { 87 int rv = 0; 88 synchronized (lock) { 89 if (isBlocking) waitOn(lock); 90 rv = set.size(); 91 } 92 return rv; 93 } 94 95 public SyncObjectIdSet snapshot() { 96 SyncObjectIdSetImpl rv = new SyncObjectIdSetImpl(); 97 synchronized (lock) { 98 if (isBlocking) waitOn(lock); 99 rv.addAll(set); 100 } 101 return rv; 102 } 103 104 private static void waitOn(Object l) { 105 try { 106 l.wait(); 107 } catch (InterruptedException e) { 108 Thread.currentThread().interrupt(); 109 } 110 } 111 } 112 | Popular Tags |