Hashmap&&redis Concurrent problem

Source: Internet
Author: User
Tags map data structure

1. A few days ago when a bug was modified, a Java data result concurrency problem was found. The approximate process is as follows:
The bean's data results are as follows, which contains a map, primarily to record the number of users used.

 Public  class Bean {    Privatemap<string,string> map =NewHashmap<string,string> ();PrivateString userId;Private intCount =0;@Override     Public int hashcode() {Final intPrime = to;intresult =1;        result = Prime * result + count; result = Prime * result + ((map = =NULL) ?0: Map.hashcode ()); result = Prime * result + (UserId = =NULL) ?0: Userid.hashcode ());returnResult }@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     PublicStringtoString() {return "Bean [map="+ Map +", userid="+ UserId +", count="+ Count +"]"; } PublicMap<string, string>Getmap() {returnMap } Public void Setmap(map<string, string> Map) { This. map = map; } PublicStringgetUserId() {returnUserId; } Public void Setuserid(String userId) { This. UserID = userid; } Public int GetCount() {returnCount } Public void SetCount(intCount) { This. Count = Count; }/** * @param args * *     Public Static void Main(string[] args) {//TODO auto-generated method stub}}

Runnable:

 Public  class taskrunnable implements Runnable{    Private intOperationnumber; Public taskrunnable(intA) { This. Operationnumber = A; }@Override     Public void Run() {Action action =NewAction ();        Bean bean = Action.getandupdatebeanfromcache (); System.out.println ("ThreadId is id ="+ Thread.CurrentThread (). GetId ());if(bean==NULL) {bean =NewBean (); Bean.setuserid ("12344"); Bean.setcount ( One);        } map<string,string> Map = Bean.getmap (); Map.put (operationnumber+"", operationnumber+""); System.out.println ("Map key ="+ Operationnumber +" ,"+"value ="+ Operationnumber); Redisutil.setcache (Redisconstant.testkey,NewGson (). ToJson (bean)); }}

Action:

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

MainClass:

publicclass MainClass {    publicstaticvoidmain(String[] args) throws InterruptedException {        for(int0;i<100;i++){            new Thread(new//启动一百个线程测试            t.start();        }    }}

The problem occurs, the start of the 100 threads is not no count is recorded, the main reason is because hashmap this data structure in the concurrency when there are some problems, but how to solve this problem, finally using the Redis Hash map data structure recorded the user's use, There is no concurrency problem tested. The main reason is that Redis is a single-threaded program, where HASHMAP does not cause this concurrency problem.

2. Zeng Xianjie Large-scale website system and Java middleware Practice
Give an example in this book, similar to this one, as follows:

publicclass TestClass {    privatenew HashMap<String,Integer>();    publicvoidadd(String key){        value = map.get(key);        if(value==null){            1);        }else{            value+1);        }    }}

Although this method can be counted correctly, but in high concurrency, it has a very bad effect on performance and low efficiency. Change the map to the CONCURRENTHASHMAP structure with the following code:

publicclass TestClass {    privatenew ConcurrentHashMap<String,Integer>();    publicvoidadd(String key){        value = map.get(key);        if(value==null){            1);        }else{            value+1);        }    }}

This way of writing can obviously cause problems with high-concurrency threads.
--the road long its repair far XI, I will go up and down and quest!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Hashmap&&redis Concurrent problem

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.