HashMap&&Redis Concurrent Problem

1.前几天修改一个bug的时候发现一个Java数据结果并发的问题。大致过程如下:
其中Bean的数据结果如下,其中包含一个Map,主要是为了记录用户的使用次数。

public class Bean {
    private Map<String,String> map = new HashMap<String,String>();
    private String userId;
    private int count = 0;
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + count;
        result = prime * result + ((map == null) ? 0 : map.hashCode());
        result = prime * result + ((userId == null) ? 0 : userId.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Bean other = (Bean) obj;
        if (count != other.count)
            return false;
        if (map == null) {
            if (other.map != null)
                return false;
        } else if (!map.equals(other.map))
            return false;
        if (userId == null) {
            if (other.userId != null)
                return false;
        } else if (!userId.equals(other.userId))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Bean [map=" + map + ", userId=" + userId + ", count=" + count + "]";
    }
    public Map<String, String> getMap() {
        return map;
    }
    public void setMap(Map<String, String> map) {
        this.map = map;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}

Runnable:

public class TaskRunnable implements Runnable{
    private int operationNumber;
    public TaskRunnable(int a){
        this.operationNumber = a;
    }
    @Override
    public void run() {
        Action action = new Action();
        Bean bean = action.getAndUpdateBeanFromCache();
        System.out.println("threadId is id = " + Thread.currentThread().getId());
        if(bean==null){
            bean = new Bean();
            bean.setUserId("12344");
            bean.setCount(11);
        }
        Map<String,String> map = bean.getMap();
        map.put(operationNumber+"",operationNumber+"");
        System.out.println("map key = " + operationNumber + " ," + " value = " + operationNumber);
        RedisUtil.setCache(RedisConstant.testKey, new Gson().toJson(bean));
    }
}

Action:

public class Action {
    public Bean getAndUpdateBeanFromCache(){
        Bean bean = new Bean();
        String key = RedisConstant.testKey;
        String value = RedisUtil.getCache(key);
        Type type = new TypeToken<Bean>(){}.getType();
        bean = new Gson().fromJson(value,type);
        return bean;
    }
}

MainClass:

public class MainClass {
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0;i<100;i++){
            Thread t = new Thread(new TaskRunnable(i)); //启动一百个线程测试
            t.start();
        }
    }
}

出现的问题,启动的一百个线程中并不是没有count都被记录下来,主要原因是因为HashMap这种数据结构在并发的时候存在一定的问题,但是如何解决这个问题,最后采用了Redis Hash Map的数据结构记录了用户的使用,经测试不会出现并发问题。主要原因是Redis是个单线程运行的程序,其中HashMap并不会出现这个并发的问题。

2.曾宪杰 大型网站系统与Java中间件实践
在这个本书中举出一个例子,跟这个很相似,如下:

public class TestClass {
    private HashMap<String,Integer> map = new HashMap<String,Integer>();
    public synchronized void add(String key){
        Integer value = map.get(key);
        if(value==null){
            map.put(key, 1);
        }else{
            map.put(key, value+1);
        }
    }
}

这个方法虽然能够正确的计数,但是在高并发的时候,却十分的影响性能,效率不高。将Map换成ConcurrentHashMap这个结构,代码如下:

public class TestClass {
    private ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap<String,Integer>();
    public void add(String key){
        Integer value = map.get(key);
        if(value==null){
            map.put(key, 1);
        }else{
            map.put(key, value+1);
        }
    }
}

这样的写法显然会造成高并发的线程的问题。
—-路漫漫其修远兮,吾将上下而求索!

HashMapConcurrentHashMap都是Java中常用的Map实现类,它们有以下几个主要区别: 1. 线程安全性:HashMap是非线程安全的,而ConcurrentHashMap是线程安全的。在多线程环境下使用HashMap可能会导致竞态条件和数据不一致的问题,而ConcurrentHashMap通过使用锁分段技术(Segment)或CAS操作来实现线程安全。 2. 并发性能:ConcurrentHashMap在并发访问时能够提供较好的性能。它通过将数据分割成多个段(Segment),每个段都拥有自己的锁,不同的线程可以同时访问不同的段,从而提高并发性能。而HashMap在并发访问时需要手动添加同步措施,性能较低。 3. 迭代器弱一致性:ConcurrentHashMap的迭代器是弱一致的,即在迭代过程中允许其他线程对Map进行修改,但不保证迭代器一定能够反映出最新的修改。而HashMap的迭代器是快速失败的,即在迭代过程中如果有其他线程对Map进行修改,会立即抛出ConcurrentModificationException异常。 4. Null键和null值:HashMap允许使用null作为键和值,而ConcurrentHashMap不允许使用null作为键和值。在ConcurrentHashMap中,如果使用null作为键或值,可能会抛出NullPointerException异常。 综上所述,HashMap适用于单线程环境或者在多线程环境下通过手动添加同步措施保证线程安全;而ConcurrentHashMap适用于多线程环境下需要高并发性能和线程安全性的场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值