Skip to content

Instantly share code, notes, and snippets.

@jnizet
Created April 6, 2014 13:18
Show Gist options
  • Save jnizet/10005906 to your computer and use it in GitHub Desktop.
Save jnizet/10005906 to your computer and use it in GitHub Desktop.
Test to show how iterating on a synchronized collection causes exception if another thread modifies it
package com.foo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class SynchronizedCollectionIteration {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(1);
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1_000_000; i++) {
list.add(i);
}
final List<Integer> synchronizedList = Collections.synchronizedList(list);
Runnable iteration = new Runnable() {
@Override
public void run() {
try {
latch.await();
for (Integer i : synchronizedList) {
System.out.println("i = " + i);
}
}
catch (InterruptedException e) {
// stop running
}
}
};
Runnable modification = new Runnable() {
@Override
public void run() {
try {
latch.await();
while (!synchronizedList.isEmpty()) {
synchronizedList.remove(0);
}
}
catch (InterruptedException e) {
// stop running
}
}
};
Thread t1 = new Thread(iteration);
Thread t2 = new Thread(modification);
t1.start();
t2.start();
latch.countDown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment