Last active
February 22, 2022 11:41
-
-
Save froop/edef3a98ff0e5a62bb5974f30db78498 to your computer and use it in GitHub Desktop.
[Java] ArrayListを複数スレッドから使用した場合に発生する競合のテスト
This file contains hidden or 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
public class TestRaceConditionOfArrayList { | |
private static final int NUMBER_OF_TRIALS = 1_000_000; | |
private static final int NUMBER_OF_THREADS = 8; | |
private static final List<Integer> SOURCE_LIST = Arrays.asList(1, 2); | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS); | |
List<Future<String>> futures = new ArrayList<>(); | |
Testee testee = new Testee(); | |
for (int i = 0; i < NUMBER_OF_TRIALS; i++) { | |
futures.add(executor.submit(testee)); | |
} | |
print(count(futures)); | |
executor.shutdown(); | |
} | |
static class Testee implements Callable<String> { | |
ArrayList<Integer> testeeList = new ArrayList<>(); | |
@Override | |
public String call() { | |
testeeList = new ArrayList<>(); | |
for (int item : SOURCE_LIST) { | |
testeeList.add(item); | |
} | |
return new ArrayList<>(testeeList).toString(); | |
} | |
} | |
static Map<String, Integer> count(List<Future<String>> futures) | |
throws InterruptedException, ExecutionException { | |
Map<String, Integer> countMap = new HashMap<>(); | |
for (Future<String> res : futures) { | |
String key = res.get(); | |
countMap.put(key, countMap.containsKey(key) ? countMap.get(key) + 1 : 1); | |
} | |
return countMap; | |
} | |
static void print(Map<String, Integer> countMap) { | |
List<Entry<String, Integer>> sortedEntries = sort(countMap); | |
for (Entry<String, Integer> item : sortedEntries) { | |
System.out.println(item); | |
} | |
} | |
static List<Entry<String, Integer>> sort(Map<String, Integer> countMap) { | |
List<Entry<String, Integer>> res = new ArrayList<>(countMap.entrySet()); | |
Collections.sort(res, new Comparator<Entry<String, Integer>>() { | |
public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) { | |
return obj2.getValue().compareTo(obj1.getValue()); // descending order of value | |
} | |
}); | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment