Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Created May 24, 2014 15:46
Show Gist options
  • Save anoopelias/0ba429c21bb6fa447e3e to your computer and use it in GitHub Desktop.
Save anoopelias/0ba429c21bb6fa447e3e to your computer and use it in GitHub Desktop.
package jperftest;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Test;
public class MapSynchronizationTest {
@Test
public void test_map_synch() throws InterruptedException,
ExecutionException {
Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
//new HashMap<>();
//new ConcurrentHashMap<>();
List<Future<Boolean>> futures = new ArrayList<>();
int n = 100;
ExecutorService executorService = Executors.newFixedThreadPool(n);
for (int i = 0; i < n; i++) {
Future<Boolean> future = executorService
.submit(new Case(map, i));
futures.add(future);
}
for (Future<Boolean> future : futures)
assertTrue(future.get());
}
private class Case implements Callable<Boolean> {
private Map<String, String> map;
private int id;
private Case(Map<String, String> map, int id) {
this.id = id;
this.map = map;
}
@Override
public Boolean call() throws Exception {
Boolean isConsistent = true;
for (int i = 0; i < 100; i++) {
String key = id + "_key_" + i;
String val = id + "_val_" + i;
map.put(key, val);
String newVal = map.get(key);
if (newVal == null || !val.equals(newVal)) {
isConsistent = false;
break;
}
}
return isConsistent;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment