AtomicLongMap
public class GuavaTest {
AtomicLongMap<String> map = AtomicLongMap.create();
Map<String, Integer> map2 = new HashMap<String, Integer>();
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
ConcurrentHashMap<String, Integer> map3 = new ConcurrentHashMap<String, Integer>();
private int taskCount = 100;
CountDownLatch latch = new CountDownLatch(taskCount);
public static void main(String[] args) {
GuavaTest t = new GuavaTest();
t.test();
}
private void test(){
for(int i=1; i<=taskCount; i++){
Thread t = new Thread(new MyTask("key", 100));
t.start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("##### AtomicLongMap #####");
for(String key : map.asMap().keySet()){
System.out.println(key + ": " + map.get(key));
}
System.out.println("##### HashMap #####");
for(String key : map2.keySet()){
System.out.println(key + ": " + map2.get(key));
}
System.out.println("##### ConcurrentHashMap #####");
for(String key : map3.keySet()){
System.out.println(key + ": " + map3.get(key));
}
}
class MyTask implements Runnable{
private String key;
private int count = 0;
public MyTask(String key, int count){
this.key = key;
this.count = count;
}
@Override
public void run() {
try {
for(int i=0; i<count; i++){
map.incrementAndGet(key);
lock.writeLock().lock();
try{
if(map2.containsKey(key)){
map2.put(key, map2.get(key)+1);
}else{
map2.put(key, 1);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
lock.writeLock().unlock();
}
if(map3.containsKey(key)){
map3.put(key, map3.get(key)+1);
}else{
map3.put(key, 1);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
##### AtomicLongMap #####
key: 10000
##### HashMap #####
key: 10000
##### ConcurrentHashMap #####
key: 9311