The Collection interface is conceptually broken into two parts for purposes of synchronization control. The purely inspective reader operations 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,
synchronizationFailures().
Non-zero values may indicate serious program errors.
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);
}
...
}
Introduction to this package., LayeredSync, TimeoutSync
| Modifier and Type | Class and Description |
|---|---|
| public class |
| Modifier and Type | Field and Description |
|---|---|
| protected final Collection | |
| protected final Sync | |
| protected final SynchronizedLong | |
| protected final Sync |
| Access | Constructor 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. |
| Modifier and Type | Method and Description |
|---|---|
| public boolean | add(Object
element whose presence in this collection is to be ensured o)Implements java. |
| public boolean | addAll(Collection<E>
collection containing elements to be added to this collection coll)Implements java. |
| protected void | |
| protected boolean | |
| public void | clear()
Implements java. |
| public boolean | contains(Object
element whose presence in this collection is to be tested o)Implements java. 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. true if this collection contains all of the elements
in the specified collection.
|
| public boolean | isEmpty()
Implements java. true if this collection contains no elements.
|
| public Iterator | iterator()
Implements java. |
| public Sync | |
| public boolean | remove(Object
element to be removed from this collection, if present o)Implements java. |
| public boolean | removeAll(Collection<E>
collection containing elements to be removed from this collection coll)Implements java. |
| public boolean | retainAll(Collection<E>
collection containing elements to be retained in this collection coll)Implements java. |
| public int | |
| public long | |
| public Object[] | toArray()
Implements java. |
| 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. |
| public Iterator | |
| public Sync |
| 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_ | |
| SyncCollection | back 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()); | |
| SyncCollection | back 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());
| |
| SyncCollection | back 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. | |
| add | back to summary |
|---|---|
| public boolean add(Object o) Implements java. Doc from java. Ensures that this collection contains the specified element (optional
operation). Returns
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
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
| |
| addAll | back to summary |
|---|---|
| public boolean addAll(Collection<E> coll) Implements java. Doc from java. 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.
| |
| afterRead | back to summary |
|---|---|
| protected void afterRead(boolean wasInterrupted) Clean up after a reader operation | |
| beforeRead | back to summary |
|---|---|
| protected boolean beforeRead() Try to acquire sync before a reader operation; record failure | |
| clear | back to summary |
|---|---|
| public void clear() Implements java. Doc from java. Removes all of the elements from this collection (optional operation). The collection will be empty after this method returns. | |
| contains | back to summary |
|---|---|
| public boolean contains(Object o) Implements java. Doc from java. Returns
| |
| containsAll | back to summary |
|---|---|
| public boolean containsAll(Collection<E> coll) Implements java. Doc from java. Returns
| |
| isEmpty | back to summary |
|---|---|
| public boolean isEmpty() Implements java. Doc from java. Returns
| |
| iterator | back to summary |
|---|---|
| public Iterator Implements java. Doc from java. 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).
| |
| readerSync | back to summary |
|---|---|
| public Sync readerSync() Return the Sync object managing read-only operations | |
| remove | back to summary |
|---|---|
| public boolean remove(Object o) Implements java. Doc from java. Removes a single instance of the specified element from this
collection, if it is present (optional operation). More formally,
removes an element
| |
| removeAll | back to summary |
|---|---|
| public boolean removeAll(Collection<E> coll) Implements java. Doc from java. 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.
| |
| retainAll | back to summary |
|---|---|
| public boolean retainAll(Collection<E> coll) Implements java. Doc from java. 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.
| |
| size | back to summary |
|---|---|
| public int size() Implements java. Doc from java. Returns the number of elements in this collection. If this collection
contains more than
| |
| syncFailures | back to summary |
|---|---|
| public long syncFailures() Return the number of synchronization failures for read-only operations | |
| toArray | back to summary |
|---|---|
| public Object[] toArray() Implements java. Doc from java. 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 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.
| |
| toArray | back to summary |
|---|---|
| public Object[] toArray(Object[] a) Implements java. Doc from java. 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
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. | |
| unprotectedIterator | back to summary |
|---|---|
| public Iterator Return the base iterator of the underlying collection | |
| writerSync | back to summary |
|---|---|
| public Sync writerSync() Return the Sync object managing mutative operations | |
| Modifier and Type | Field and Description |
|---|---|
| protected final Iterator |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| public boolean | |
| public Object | |
| public void | remove()
Overrides default java. |
| baseIterator_ | back to summary |
|---|---|
| protected final Iterator<E> baseIterator_ | |
| SyncCollectionIterator | back to summary |
|---|---|
| pack-priv SyncCollectionIterator(Iterator<E> baseIterator) | |
| hasNext | back to summary |
|---|---|
| public boolean hasNext() Implements java. Doc from java. Returns
| |
| next | back to summary |
|---|---|
| public Object next() Implements java. Doc from java. Returns the next element in the iteration.
| |
| remove | back to summary |
|---|---|
| public void remove() Overrides default java. Doc from java. Removes from the underlying collection the last element returned
by this iterator (optional operation). This method can be called
only once per call to 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 | |