KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > SyncObjectIdSetImpl


1 /*
2  * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
3  * notice. All rights reserved.
4  */

5 package com.tc.util;
6
7 import java.util.AbstractSet JavaDoc;
8 import java.util.Collection JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.Set JavaDoc;
11
12 public class SyncObjectIdSetImpl extends AbstractSet JavaDoc implements SyncObjectIdSet {
13
14   private final Object JavaDoc lock = new Object JavaDoc();
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 JavaDoc obj) {
36     synchronized (lock) {
37       return set.add(obj);
38     }
39   }
40
41   public void addAll(Set JavaDoc s) {
42     synchronized (lock) {
43       set.addAll(s);
44     }
45   }
46
47   public boolean contains(Object JavaDoc 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 JavaDoc 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 JavaDoc 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 JavaDoc iterator() {
78     Iterator JavaDoc 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 JavaDoc l) {
105     try {
106       l.wait();
107     } catch (InterruptedException JavaDoc e) {
108       Thread.currentThread().interrupt();
109     }
110   }
111 }
112
Popular Tags