001: /*
002: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
003: * notice. All rights reserved.
004: */
005: package com.tc.util;
006:
007: import java.util.AbstractSet;
008: import java.util.Collection;
009: import java.util.Iterator;
010: import java.util.Set;
011:
012: public class SyncObjectIdSetImpl extends AbstractSet implements
013: SyncObjectIdSet {
014:
015: private final Object lock = new Object();
016: private ObjectIDSet2 set = new ObjectIDSet2();
017: private boolean isBlocking = false;
018:
019: public void startPopulating() {
020: synchronized (lock) {
021: isBlocking = true;
022: }
023: }
024:
025: public void stopPopulating(ObjectIDSet2 fullSet) {
026: synchronized (lock) {
027: ObjectIDSet2 large = (fullSet.size() > set.size()) ? fullSet
028: : set;
029: ObjectIDSet2 small = (set == large) ? fullSet : set;
030: large.addAll(small);
031: set = large;
032: isBlocking = false;
033: lock.notifyAll();
034: }
035: }
036:
037: public boolean add(Object obj) {
038: synchronized (lock) {
039: return set.add(obj);
040: }
041: }
042:
043: public void addAll(Set s) {
044: synchronized (lock) {
045: set.addAll(s);
046: }
047: }
048:
049: public boolean contains(Object o) {
050: boolean rv = false;
051: synchronized (lock) {
052: rv = set.contains(o);
053: if (isBlocking && !rv) {
054: waitWhileBlocked();
055: rv = set.contains(o);
056: }
057: }
058: return rv;
059: }
060:
061: public boolean removeAll(Collection ids) {
062: boolean rv = false;
063: synchronized (lock) {
064: waitWhileBlocked();
065: rv = set.removeAll(ids);
066: }
067: return rv;
068: }
069:
070: public boolean remove(Object o) {
071: boolean rv = false;
072: synchronized (lock) {
073: waitWhileBlocked();
074: rv = set.remove(o);
075: }
076: return rv;
077: }
078:
079: public Iterator iterator() {
080: Iterator rv = null;
081: synchronized (lock) {
082: waitWhileBlocked();
083: rv = set.iterator();
084: }
085: return rv;
086: }
087:
088: public int size() {
089: int rv = 0;
090: synchronized (lock) {
091: waitWhileBlocked();
092: rv = set.size();
093: }
094: return rv;
095: }
096:
097: public ObjectIDSet2 snapshot() {
098: synchronized (lock) {
099: waitWhileBlocked();
100: return new ObjectIDSet2(set);
101: }
102: }
103:
104: private void waitWhileBlocked() {
105: try {
106: while (isBlocking) {
107: lock.wait();
108: }
109: } catch (InterruptedException e) {
110: Thread.currentThread().interrupt();
111: }
112: }
113: }
|