Created
September 5, 2012 00:23
-
-
Save fizzy33/3628474 to your computer and use it in GitHub Desktop.
Show how quickly java.util collections break in a multi-threaded environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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