001    package railo.commons.util.mod;
002    
003    import java.io.IOException;
004    import java.io.ObjectOutputStream;
005    import java.io.Serializable;
006    import java.util.Collection;
007    import java.util.Iterator;
008    
009    public class SyncCollection<E> implements Collection<E>, Serializable {
010            private static final long serialVersionUID = 3053995032091335093L;
011    
012            final Collection<E> c;  // Backing Collection
013            final Object mutex;     // Object on which to synchronize
014    
015            SyncCollection(Collection<E> c) {
016                if (c==null)
017                    throw new NullPointerException();
018                this.c = c;
019                mutex = this;
020            }
021            SyncCollection(Collection<E> c, Object mutex) {
022                this.c = c;
023                this.mutex = mutex;
024            }
025    
026            public int size() {
027                synchronized (mutex) {return c.size();}
028            }
029            public boolean isEmpty() {
030                synchronized (mutex) {return c.isEmpty();}
031            }
032            public boolean contains(Object o) {
033                synchronized (mutex) {return c.contains(o);}
034            }
035            public Object[] toArray() {
036                synchronized (mutex) {return c.toArray();}
037            }
038            public <T> T[] toArray(T[] a) {
039                synchronized (mutex) {return c.toArray(a);}
040            }
041    
042            public Iterator<E> iterator() {
043                return c.iterator(); // Must be manually synched by user!
044            }
045    
046            public boolean add(E e) {
047                synchronized (mutex) {return c.add(e);}
048            }
049            public boolean remove(Object o) {
050                synchronized (mutex) {return c.remove(o);}
051            }
052    
053            public boolean containsAll(Collection<?> coll) {
054                synchronized (mutex) {return c.containsAll(coll);}
055            }
056            public boolean addAll(Collection<? extends E> coll) {
057                synchronized (mutex) {return c.addAll(coll);}
058            }
059            public boolean removeAll(Collection<?> coll) {
060                synchronized (mutex) {return c.removeAll(coll);}
061            }
062            public boolean retainAll(Collection<?> coll) {
063                synchronized (mutex) {return c.retainAll(coll);}
064            }
065            public void clear() {
066                synchronized (mutex) {c.clear();}
067            }
068            public String toString() {
069                synchronized (mutex) {return c.toString();}
070            }
071            private void writeObject(ObjectOutputStream s) throws IOException {
072                synchronized (mutex) {s.defaultWriteObject();}
073            }
074        }