ConcurrentHashMap은 HashTable보다 훨씬 빠릅니다. 다음 코드가 왜 나타나지 않는지 궁금합니다.ConcurrentHaspMap 대 HashTable 실행 시간
다음 코드에서 일부 숫자는 ConcurrentHashMap (chm)과 HashTable (ht)에 모두 채워집니다. chm 또는 ht 요소에서 동일한 작업을 수행하고 실행 시간을 ms 단위로 반환하는 두 개의 동등한 Callable (하나는 chm 용, 다른 하나는 ht 용)이 있습니다.
hm의 실행 시간이 chm의 절반보다 짧습니다.
public class ConcurrentHashMapDemo {
static ConcurrentHashMap<Long, Double> chm;
static Hashtable<Long, Double> ht;
int result1;
int result2;
static long numbers = 1000000;
public ConcurrentHashMapDemo(){
chm = new ConcurrentHashMap<>();
ht = new Hashtable<>();
result1=0;
result2=0;
}
// just do some operation with map or table elements
private class Th1 implements Callable<Integer>{
public Integer call(){
long base = System.currentTimeMillis();
for(Entry<Long, Double> e: chm.entrySet()){
result1+=e.getKey();
result1+=(int)(e.getValue()*10);
}
long time = System.currentTimeMillis();
return (int)(time-base);
}
}
private class Th2 implements Callable<Integer>{
public Integer call(){
long base = System.currentTimeMillis();
for(Entry<Long, Double> e: ht.entrySet()){
result2+=e.getKey();
result2+=(int)(e.getValue()*10);
}
long time = System.currentTimeMillis();
return (int)(time-base);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcurrentHashMapDemo chmd = new ConcurrentHashMapDemo();
for(long i=0;i<numbers;i++){
chm.put((Long)i, Math.sqrt(i));
ht.put((Long)i, Math.sqrt(i));
}
ExecutorService ex = Executors.newCachedThreadPool();
try {
Future<Integer>s11 = ex.submit(chmd.new Th1());
System.out.println("chm "+s11.get()); // appr. 220
Thread.sleep(1000);
Future<Integer>s21 = ex.submit(chmd.new Th2());
System.out.println("ht "+s21.get()); // appr. 110
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
ex.shutdown();
}
}