Top Description Inners Fields Constructors Methods
EDU.oswego.cs.dl.util.concurrent

public Class SyncCollection

extends Object
implements Collection
Class Inheritance
All Implemented Interfaces
java.util.Collection, java.lang.Iterable
Known Direct Subclasses
EDU.oswego.cs.dl.util.concurrent.SyncList, EDU.oswego.cs.dl.util.concurrent.SyncSet
Imports
java.util.*

SyncCollections wrap Sync-based control around java.util.Collections. They are similar in operation to those provided by java.util.Collection.synchronizedCollection, but have several extended capabilities.

The Collection interface is conceptually broken into two parts for purposes of synchronization control. The purely inspective reader operations are:

The possibly mutative writer operations (which are also the set of operations that are allowed to throw UnsupportedOperationException) are:

SyncCollections can be used with either Syncs or ReadWriteLocks. When used with single Syncs, the same lock is used as both the reader and writer lock. The SyncCollection class cannot itself guarantee that using a pair of read/write locks will always correctly protect objects, since Collection implementations are not precluded from internally performing hidden unprotected state changes within conceptually read-only operations. However, they do work with current java.util implementations. (Hopefully, implementations that do not provide this natural guarantee will be clearly documentented as such.)

This class provides a straight implementation of Collections interface. In order to conform to this interface, sync failures due to interruption do NOT result in InterruptedExceptions. Instead, upon detection of interruption,

The iterator() method returns a SyncCollectionIterator with properties and methods that are analogous to those of SyncCollection itself: hasNext and next are read-only, and remove is mutative. These methods allow fine-grained controlled access, but do NOT preclude concurrent modifications from being interleaved with traversals, which may lead to ConcurrentModificationExceptions. However, the class also supports method unprotectedIterator that can be used in conjunction with the readerSync or writerSync methods to perform locked traversals. For example, to protect a block of reads:

   Sync lock = coll.readerSync();
   try {
     lock.acquire();
     try {
       Iterator it = coll.unprotectedIterator();
       while (it.hasNext()) 
         System.out.println(it.next());
     }
     finally {
       lock.release();
     }
  }
  catch (InterruptedException ex) { ... }
If you need to protect blocks of writes, you must use some form of reentrant lock (for example ReentrantLock or ReentrantWriterPreferenceReadWriteLock) as the Sync for the collection in order to allow mutative methods to proceed while the current thread holds the lock. For example, you might need to hold a write lock during an initialization sequence:
  Collection c = new SyncCollection(new ArrayList(), 
                                    new ReentrantWriterPreferenceReadWriteLock());
  // ...
  c.writeLock().acquire();
  try {
    for (...) {
      Object x = someStream.readObject();
      c.add(x); // would block if writeLock not reentrant
    }
  }
  catch (IOException iox) {
    ...
  }
  finally {
    c.writeLock().release();
  }
  catch (InterruptedException ex) { ... }

(It would normally be better practice here to not make the collection accessible until initialization is complete.)

This class does not specifically support use of timed synchronization through the attempt method. However, you can obtain this effect via the TimeoutSync class. For example:

Mutex lock = new Mutex();
TimeoutSync timedLock = new TimeoutSync(lock, 1000); // 1 sec timeouts
Collection c = new SyncCollection(new HashSet(), timedlock);

The same can be done with read-write locks:

ReadWriteLock rwl = new WriterPreferenceReadWriteLock();
Sync rlock = new TimeoutSync(rwl.readLock(), 100);
Sync wlock = new TimeoutSync(rwl.writeLock(), 100);
Collection c = new SyncCollection(new HashSet(), rlock, wlock);

In addition to synchronization control, SyncCollections may be useful in any context requiring before/after methods surrounding collections. For example, you can use ObservableSync to arrange notifications on method calls to collections, as in:

class X {
  Collection c;

  static class CollectionObserver implements ObservableSync.SyncObserver {
    public void onAcquire(Object arg) {
      Collection coll = (Collection) arg;
      System.out.println("Starting operation on" + coll);
      // Other plausible responses include performing integrity
      //   checks on the collection, updating displays, etc
    }
    public void onRelease(Object arg) {
      Collection coll = (Collection) arg;
      System.out.println("Finished operation on" + coll);
    }
  }

  X() {
    ObservableSync s = new ObservableSync();
    c = new SyncCollection(new HashSet(), s);
    s.setNotificationArgument(c);
    CollectionObserver obs = new CollectionObserver();
    s.attach(obs);
  }
  ...
}
See Also
Introduction to this package., LayeredSync, TimeoutSync

Nested and Inner Type Summary

Modifier and TypeClass and Description
public class

Field Summary

Modifier and TypeField and Description
protected final Collection<E>
protected final Sync
protected final SynchronizedLong
protected final Sync

Constructor Summary

AccessConstructor and Description
public
SyncCollection(Collection<E> collection, Sync sync)

Create a new SyncCollection protecting the given collection, and using the given sync to control both reader and writer methods.

public
SyncCollection(Collection<E> collection, ReadWriteLock rwl)

Create a new SyncCollection protecting the given collection, and using the given ReadWriteLock to control reader and writer methods.

public
SyncCollection(Collection<E> collection, Sync readLock, Sync writeLock)

Create a new SyncCollection protecting the given collection, and using the given pair of locks to control reader and writer methods.

Method Summary

Modifier and TypeMethod and Description
public boolean
add(Object
element whose presence in this collection is to be ensured
o
)

Implements java.util.Collection.add.

Ensures that this collection contains the specified element (optional operation).
public boolean
addAll(Collection<E>
collection containing elements to be added to this collection
coll
)

Implements java.util.Collection.addAll.

Adds all of the elements in the specified collection to this collection (optional operation).
protected void
afterRead(boolean wasInterrupted)

Clean up after a reader operation

protected boolean
beforeRead()

Try to acquire sync before a reader operation; record failure

public void
clear()

Implements java.util.Collection.clear.

Removes all of the elements from this collection (optional operation).
public boolean
contains(Object
element whose presence in this collection is to be tested
o
)

Implements java.util.Collection.contains.

Returns true if this collection contains the specified element.
public boolean
containsAll(Collection<E>
collection to be checked for containment in this collection
coll
)

Implements java.util.Collection.containsAll.

Returns true if this collection contains all of the elements in the specified collection.
public boolean
isEmpty()

Implements java.util.Collection.isEmpty.

Returns true if this collection contains no elements.
public Iterator<E>
iterator()

Implements java.util.Collection.iterator.

Returns an iterator over the elements in this collection.
public Sync
readerSync()

Return the Sync object managing read-only operations

public boolean
remove(Object
element to be removed from this collection, if present
o
)

Implements java.util.Collection.remove.

Removes a single instance of the specified element from this collection, if it is present (optional operation).
public boolean
removeAll(Collection<E>
collection containing elements to be removed from this collection
coll
)

Implements java.util.Collection.removeAll.

Removes all of this collection's elements that are also contained in the specified collection (optional operation).
public boolean
retainAll(Collection<E>
collection containing elements to be retained in this collection
coll
)

Implements java.util.Collection.retainAll.

Retains only the elements in this collection that are contained in the specified collection (optional operation).
public int
size()

Implements java.util.Collection.size.

Returns the number of elements in this collection.
public long
syncFailures()

Return the number of synchronization failures for read-only operations

public Object[]
toArray()

Implements java.util.Collection.toArray.

Returns an array containing all of the elements in this collection.
public Object[]
toArray(Object[]
the array into which the elements of this collection are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
a
)

Implements java.util.Collection.toArray.

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
public Iterator<E>
unprotectedIterator()

Return the base iterator of the underlying collection

public Sync
writerSync()

Return the Sync object managing mutative operations

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

c_back to summary
protected final Collection<E> c_
rd_back to summary
protected final Sync rd_
syncFailures_back to summary
protected final SynchronizedLong syncFailures_
wr_back to summary
protected final Sync wr_

Constructor Detail

SyncCollectionback to summary
public SyncCollection(Collection<E> collection, Sync sync)

Create a new SyncCollection protecting the given collection, and using the given sync to control both reader and writer methods. Common, reasonable choices for the sync argument include Mutex, ReentrantLock, and Semaphores initialized to 1.

Sample Usage

Collection c = new SyncCollection(new ArrayList(), new Mutex()); 
SyncCollectionback to summary
public SyncCollection(Collection<E> collection, ReadWriteLock rwl)

Create a new SyncCollection protecting the given collection, and using the given ReadWriteLock to control reader and writer methods.

Sample Usage

Collection c = new SyncCollection(new HashSet(), 
                                  new WriterPreferenceReadWriteLock());
SyncCollectionback to summary
public SyncCollection(Collection<E> collection, Sync readLock, Sync writeLock)

Create a new SyncCollection protecting the given collection, and using the given pair of locks to control reader and writer methods.

Method Detail

addback to summary
public boolean add(Object o)

Implements java.util.Collection.add.

Doc from java.util.Collection.add.

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)

Collections that support this operation may place limitations on what elements may be added to this collection. In particular, some collections will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

Parameters
o:Object

element whose presence in this collection is to be ensured

Returns:boolean

true if this collection changed as a result of the call

addAllback to summary
public boolean addAll(Collection<E> coll)

Implements java.util.Collection.addAll.

Doc from java.util.Collection.addAll.

Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection, and this collection is nonempty.) If the specified collection has a defined encounter order, processing of its elements generally occurs in that order.

Parameters
coll:Collection<E>

collection containing elements to be added to this collection

Returns:boolean

true if this collection changed as a result of the call

afterReadback to summary
protected void afterRead(boolean wasInterrupted)

Clean up after a reader operation

beforeReadback to summary
protected boolean beforeRead()

Try to acquire sync before a reader operation; record failure

clearback to summary
public void clear()

Implements java.util.Collection.clear.

Doc from java.util.Collection.clear.

Removes all of the elements from this collection (optional operation). The collection will be empty after this method returns.

containsback to summary
public boolean contains(Object o)

Implements java.util.Collection.contains.

Doc from java.util.Collection.contains.

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that Objects.equals(o, e).

Parameters
o:Object

element whose presence in this collection is to be tested

Returns:boolean

true if this collection contains the specified element

containsAllback to summary
public boolean containsAll(Collection<E> coll)

Implements java.util.Collection.containsAll.

Doc from java.util.Collection.containsAll.

Returns true if this collection contains all of the elements in the specified collection.

Parameters
coll:Collection<E>

collection to be checked for containment in this collection

Returns:boolean

true if this collection contains all of the elements in the specified collection

isEmptyback to summary
public boolean isEmpty()

Implements java.util.Collection.isEmpty.

Doc from java.util.Collection.isEmpty.

Returns true if this collection contains no elements.

Returns:boolean

true if this collection contains no elements

iteratorback to summary
public Iterator<E> iterator()

Implements java.util.Collection.iterator.

Doc from java.util.Collection.iterator.

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

Returns:Iterator<E>

an Iterator over the elements in this collection

readerSyncback to summary
public Sync readerSync()

Return the Sync object managing read-only operations

removeback to summary
public boolean remove(Object o)

Implements java.util.Collection.remove.

Doc from java.util.Collection.remove.

Removes a single instance of the specified element from this collection, if it is present (optional operation). More formally, removes an element e such that Objects.equals(o, e), if this collection contains one or more such elements. Returns true if this collection contained the specified element (or equivalently, if this collection changed as a result of the call).

Parameters
o:Object

element to be removed from this collection, if present

Returns:boolean

true if an element was removed as a result of this call

removeAllback to summary
public boolean removeAll(Collection<E> coll)

Implements java.util.Collection.removeAll.

Doc from java.util.Collection.removeAll.

Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.

Parameters
coll:Collection<E>

collection containing elements to be removed from this collection

Returns:boolean

true if this collection changed as a result of the call

retainAllback to summary
public boolean retainAll(Collection<E> coll)

Implements java.util.Collection.retainAll.

Doc from java.util.Collection.retainAll.

Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.

Parameters
coll:Collection<E>

collection containing elements to be retained in this collection

Returns:boolean

true if this collection changed as a result of the call

sizeback to summary
public int size()

Implements java.util.Collection.size.

Doc from java.util.Collection.size.

Returns the number of elements in this collection. If this collection contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Returns:int

the number of elements in this collection

syncFailuresback to summary
public long syncFailures()

Return the number of synchronization failures for read-only operations

toArrayback to summary
public Object[] toArray()

Implements java.util.Collection.toArray.

Doc from java.util.Collection.toArray.

Returns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array's runtime component type is Object.

The returned array will be "safe" in that no references to it are maintained by this collection. (In other words, this method must allocate a new array even if this collection is backed by an array). The caller is thus free to modify the returned array.

Returns:Object[]

an array, whose runtime component type is Object, containing all of the elements in this collection

toArrayback to summary
public Object[] toArray(Object[] a)

Implements java.util.Collection.toArray.

Doc from java.util.Collection.toArray.

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

If this collection fits in the specified array with room to spare (i.e., the array has more elements than this collection), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.)

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

Parameters
a:Object[]

the array into which the elements of this collection are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Returns:Object[]

an array containing all of the elements in this collection

unprotectedIteratorback to summary
public Iterator<E> unprotectedIterator()

Return the base iterator of the underlying collection

writerSyncback to summary
public Sync writerSync()

Return the Sync object managing mutative operations

EDU.oswego.cs.dl.util.concurrent back to summary

public Class SyncCollection.SyncCollectionIterator

extends Object
implements Iterator
Class Inheritance
  • java.lang.Object
  • EDU.oswego.cs.dl.util.concurrent.SyncCollection.SyncCollectionIterator
All Implemented Interfaces
java.util.Iterator
Known Direct Subclasses
EDU.oswego.cs.dl.util.concurrent.SyncList.SyncCollectionListIterator

Field Summary

Modifier and TypeField and Description
protected final Iterator<E>

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public boolean
hasNext()

Implements java.util.Iterator.hasNext.

Returns true if the iteration has more elements.
public Object
next()

Implements java.util.Iterator.next.

Returns the next element in the iteration.
public void
remove()

Overrides default java.util.Iterator.remove.

Removes from the underlying collection the last element returned by this iterator (optional operation).
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

baseIterator_back to summary
protected final Iterator<E> baseIterator_

Constructor Detail

SyncCollectionIteratorback to summary
pack-priv SyncCollectionIterator(Iterator<E> baseIterator)

Method Detail

hasNextback to summary
public boolean hasNext()

Implements java.util.Iterator.hasNext.

Doc from java.util.Iterator.hasNext.

Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)

Returns:boolean

true if the iteration has more elements

nextback to summary
public Object next()

Implements java.util.Iterator.next.

Doc from java.util.Iterator.next.

Returns the next element in the iteration.

Returns:Object

the next element in the iteration

removeback to summary
public void remove()

Overrides default java.util.Iterator.remove.

Doc from java.util.Iterator.remove.

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next.

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy.

The behavior of an iterator is unspecified if this method is called after a call to the forEachRemaining method.