Skip to content

Instantly share code, notes, and snippets.

@nicholashagen
Last active December 17, 2015 10:59
Show Gist options
  • Save nicholashagen/5599362 to your computer and use it in GitHub Desktop.
Save nicholashagen/5599362 to your computer and use it in GitHub Desktop.
Faster Synchronization Through Hash Maps
public class LoadTest {
public static void main(String[] args) {
// int count = 5000;
int count = 25000;
// int count = 100000;
// int count = 250000;
long s = System.nanoTime();
for (int i = 0; i < 1000; i++) {
test3(count);
}
long e = System.nanoTime();
System.out.println("RESULT: " + ((e - s) / 1000000.0));
}
public static void test1(int count) {
final Integer value = Integer.valueOf(1);
List<Integer> list = new ArrayList<Integer>(10000);
for (int i = 0; i < count; i++) {
list.add(value);
}
}
public static void test2(int count) {
final Integer value = Integer.valueOf(1);
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>(10000));
for (int i = 0; i < count; i++) {
list.add(value);
}
}
public static void test3(int count) {
final Integer value = Integer.valueOf(1);
Map<Long, List<Integer>> list = new HashMap<Long, List<Integer>>();
for (int i = 0; i < count; i++) {
Long key = Long.valueOf(Thread.currentThread().getId());
List<Integer> sublist = list.get(key);
if (sublist == null) {
sublist = new ArrayList<Integer>(10000);
synchronized (LoadTest.class) {
list.put(key, sublist);
}
}
sublist.add(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment