1 |
// Stand-alone version of java.util.Collections.synchronizedCollection |
2 |
import java.util.*; |
3 |
import java.io.*; |
4 |
|
5 |
public final class SynchronizedCollection<E> implements Collection<E>, Serializable { |
6 |
// use serialVersionUID from JDK 1.2.2 for interoperability |
7 |
private static final long serialVersionUID = 3053995032091335093L; |
8 |
|
9 |
final Collection<E> c; // Backing Collection |
10 |
final Object mutex; // Object on which to synchronize |
11 |
|
12 |
public SynchronizedCollection(Collection<E> c) { |
13 |
if (c==null) |
14 |
throw new NullPointerException(); |
15 |
this.c = c; |
16 |
mutex = this; |
17 |
} |
18 |
public SynchronizedCollection(Collection<E> c, Object mutex) { |
19 |
this.c = c; |
20 |
this.mutex = mutex; |
21 |
} |
22 |
|
23 |
public SynchronizedCollection() { |
24 |
this(new ArrayList<E>()); |
25 |
} |
26 |
|
27 |
public final int size() { |
28 |
synchronized(mutex) {return c.size();} |
29 |
} |
30 |
public final boolean isEmpty() { |
31 |
synchronized(mutex) {return c.isEmpty();} |
32 |
} |
33 |
public final boolean contains(Object o) { |
34 |
synchronized(mutex) {return c.contains(o);} |
35 |
} |
36 |
public final Object[] toArray() { |
37 |
synchronized(mutex) {return c.toArray();} |
38 |
} |
39 |
public final <T> T[] toArray(T[] a) { |
40 |
synchronized(mutex) {return c.toArray(a);} |
41 |
} |
42 |
|
43 |
public final Iterator<E> iterator() { |
44 |
return c.iterator(); // Must be manually synched by user! |
45 |
} |
46 |
|
47 |
public final boolean add(E e) { |
48 |
synchronized(mutex) {return c.add(e);} |
49 |
} |
50 |
public final boolean remove(Object o) { |
51 |
synchronized(mutex) {return c.remove(o);} |
52 |
} |
53 |
|
54 |
public final boolean containsAll(Collection<?> coll) { |
55 |
synchronized(mutex) {return c.containsAll(coll);} |
56 |
} |
57 |
public final boolean addAll(Collection<? extends E> coll) { |
58 |
synchronized(mutex) {return c.addAll(coll);} |
59 |
} |
60 |
public final boolean removeAll(Collection<?> coll) { |
61 |
synchronized(mutex) {return c.removeAll(coll);} |
62 |
} |
63 |
public final boolean retainAll(Collection<?> coll) { |
64 |
synchronized(mutex) {return c.retainAll(coll);} |
65 |
} |
66 |
public final void clear() { |
67 |
synchronized(mutex) {c.clear();} |
68 |
} |
69 |
public final String toString() { |
70 |
synchronized(mutex) {return c.toString();} |
71 |
} |
72 |
private void writeObject(ObjectOutputStream s) throws IOException { |
73 |
synchronized(mutex) {s.defaultWriteObject();} |
74 |
} |
75 |
} |