Skip to content

Instantly share code, notes, and snippets.

@fizzy33
Created September 5, 2012 00:23
Show Gist options
  • Save fizzy33/3628474 to your computer and use it in GitHub Desktop.
Save fizzy33/3628474 to your computer and use it in GitHub Desktop.
Show how quickly java.util collections break in a multi-threaded environment
package net.model3.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ShowMeThatCME {
static List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
public static void main(String[] args) {
final int count = 9999;
for ( int i=0 ; i<count ; i++ ) {
list.add(i);
}
Thread reader = new Thread("reader") {
@Override
public void run() {
while( true ) {
int sum = 0;
for ( Integer i : list ) {
sum += i;
}
}
}
};
Thread writer = new Thread("writer") {
@Override
public void run() {
while( true ) {
for ( int i=0 ; i<count ; i++ ) {
list.add(i);
}
for ( int i=0 ; i<count ; i++ ) {
list.remove(list.size()-1);
}
}
}
};
reader.start();
writer.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment