Guard Collections With Synchronized Wrappers
Wrap a list with Collections.synchronizedList, iterate under an explicit lock, and contrast it with an unsynchronized ArrayList.
Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SynchronizedWrapperDemo {
public static void main(String[] args) throws Exception {
List<Integer> shared = Collections.synchronizedList(new ArrayList<>());
Runnable writer = () -> {
for (int i = 0; i < 1_000; i++) {
shared.add(i); // 单个 add 由包装器加锁
}
};
Thread a = new Thread(writer, "writer-a");
Thread b = new Thread(writer, "writer-b");
a.start();
b.start();
a.join();
b.join();
System.out.println("size: " + shared.size());
// 复合迭代仍需手动持有同一把锁
int sum = 0;
synchronized (shared) {
for (int value : shared) {
sum += value;
}
}
System.out.println("sum: " + sum);
// 普通 ArrayList 在并发写入下不安全,仅作单线程对照
List<String> plain = new ArrayList<>();
plain.add("single-threaded");
System.out.println("plain size: " + plain.size());
// 包装器的同步对象就是包装器自身
synchronized (shared) {
System.out.println("locked size: " + shared.size());
}
}
}How the snippet works
The working surface is the class SynchronizedWrapperDemo — everything else is wiring.
Repetition is confined to for (int i = 0; i < 1_000; i++) — the rest of the file is straight-line.
Applying it
Running the file prints labeled results such as size:, sum:, plain size: — each operation’s effect is visible in the output.
Statements that matter
List<Integer> shared = Collections.synchronizedList(new ArrayList<>());
Thread a = new Thread(writer, "writer-a");
Thread b = new Thread(writer, "writer-b");
Interactive Tools for This Topic
FAQ
- What does Guard Collections With Synchronized Wrappers print when run?
- Running the file directly is enough — expect labeled output lines such as `size:`, `sum:`, `plain size:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.