3
該類的方法getFirst()
和getSecond()
被同時調用。它是一個網絡應用程序的一部分。Java併發性,流行爲
內部映射也填充,沒有併發。
public class MyClass {
private Map<String, List<List<String>>> first;
private Map<String, List<List<String>>> second;
public MyClass() {
first = new ConcurrentHashMap<>();
second = new ConcurrentHashMap<>();
}
public Set<String> getFirst(String key, String token, int a, int b) {
return get(first, key, token, a, b);
}
public Set<String> getSecond(String key, String token, int a, int b) {
return get(second, key, token, a, b);
}
private Set<String> get(final Map<String, List<List<String>>> map, final String key, final String token,
final int a, final int b) {
Set<String> result = new TreeSet<>();
map.get(key).stream().filter(i -> i.size() <= b && i.size() >= a).forEach(
s -> result
.addAll(s.stream().filter(p -> StringUtils.containsIgnoreCase(p, token)).collect(Collectors.toList())));
return result;
}
}
我用類似ab -n 10000 -c 100
(Apache的實用工具)測試了它。我登錄它。我所有的時間都一樣。但是,如果我將map.get(key).stream()
更改爲map.get(key).parallelStream()
,並執行相同的步驟,則有時會得到不同的結果大小(始終較小)。
這是什麼?
嘗試使用線程安全集合來收集結果。 – OldCurmudgeon
Set的線程安全版本? – SDmitry
@SDmitry:爲什麼不呢? 'Collections.newSetFromMap(new ConcurrentSkipListMap())' –