|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。在散布式的程序中,cache的公道利用能够带来功能上的极年夜提拔,特别是在资本创立必要高贵的开支时。cache的计划最主要的是要包管线程平安和高效性。上面以代码为例,先容了三种cache的写法。
1.集约的加锁- publicclassCache1{privateHashMap<String,ServerGroup>route2SG=null;publicCache1(){route2SG=newHashMap<String,ServerGroup>();}publicsynchronizedServerGroupget(StringrouteKey)throwsIOException{ServerGroupsg=null;sg=route2SG.get(routeKey);if(sg==null){sg=getServerGroup(routeKey);route2SG.put(routeKey,sg);}returnsg;}publicsynchronizedvoidremove(StringrouteKey){route2SG.remove(routeKey);}privateServerGroupgetServerGroup(StringrouteKey)throwsIOException{ServerGroupsg=null;/***ConstructServerGrouphere*/returnsg;}}
复制代码 2.读写锁- publicclassCache2{privateConcurrentHashMap<String,ServerGroup>route2SG=null;privatefinalReadWriteLocklock=newReentrantReadWriteLock();publicCache2(){route2SG=newConcurrentHashMap<String,ServerGroup>();}publicServerGroupget(StringrouteKey)throwsIOException{ServerGroupsg=null;try{lock.readLock().lock();sg=route2SG.get(routeKey);if(sg==null){lock.readLock().unlock();lock.writeLock().lock();sg=route2SG.get(routeKey);if(sg==null){sg=getServerGroup(routeKey);route2SG.put(routeKey,sg);}lock.readLock().lock();lock.writeLock().unlock();}}catch(IOExceptione){lock.writeLock().unlock();throw(e);}lock.readLock().unlock();returnsg;}publicvoidremove(StringrouteKey){try{lock.writeLock().lock();route2SG.remove(routeKey);}finally{lock.writeLock().unlock();}}privateServerGroupgetServerGroup(StringrouteKey)throwsIOException{ServerGroupsg=null;/***ConstructServerGrouphere*/returnsg;}}
复制代码 3.无锁- publicclassCache3{privateConcurrentHashMap<String,FutureTask<ServerGroup>>route2SGFT=null;publicCache3(){route2SGFT=newConcurrentHashMap<String,FutureTask<ServerGroup>>();}publicServerGroupget(StringrouteKey)throwsIOException,InterruptedException,ExecutionException{FutureTask<ServerGroup>ft=route2SGFT.get(routeKey);if(ft!=null){returnft.get();}FutureTask<ServerGroup>sft=newFutureTask<ServerGroup>(newConstructSGTask(routeKey));FutureTask<ServerGroup>old=route2SGFT.putIfAbsent(routeKey,sft);if(old==null){old=sft;old.run();}returnold.get();}publicvoidremove(StringrouteKey){route2SGFT.remove(routeKey);}classConstructSGTaskimplementsCallable<ServerGroup>{privatefinalStringkey;publicConstructSGTask(Stringkey){super();this.key=key;}@OverridepublicServerGroupcall()throwsException{returngetServerGroup(key);}}privateServerGroupgetServerGroup(StringrouteKey)throwsIOException{ServerGroupsg=null;/***ConstructServerGrouphere*/returnsg;}}
复制代码 总结,
从三份代码中能够看出,锁的粒度从集约到无,这个就极年夜的进步了cache的并发性。
j2EE和asp比较,其实也没什么比的,原因和我上面说那些比较差不了多少,也是稳定性,安全性,J2EE比asp高,速度上比不过asp,asp也是延续着它的拖拽控件的方法,提高速度。 |
|