花果山第一届猿类分级考试实录--Talk is cheap,Show me the code
本故事純屬虛構(gòu),如有雷同,純屬巧合!
故事背景
?
悟空師徒4人取經(jīng)回來(lái)后,因不耐收到管教,就回到了花果山,帶領(lǐng)一幫猴子猴孫逍遙自在的過(guò)日子,奈何因在閻王殿里將生死薄中的猴子猴孫的名字都劃去了,猴子猴孫是越來(lái)越多。
?
悟空最是沒(méi)有耐心的,無(wú)法一一管教,隨向太白金星討教。
?
猿類(lèi)分級(jí)考試
太白金星給了主意:考試分級(jí)。
并且給出了題目:
創(chuàng)建一個(gè)通用的計(jì)數(shù)器,能計(jì)量很多的東西,如金箍棒。
?
參考答案如下:
猿類(lèi)分階:一~九等級(jí) 依次上升
一階猿類(lèi)
public class Counter1 {private static int cnt=0;public int increase() {return ++cnt;}public int decrease() {return --cnt;} }?
旁白:實(shí)現(xiàn)了功能。
二階猿類(lèi)
public class Counter2 {private static long cnt=0;public long increase() {return ++cnt;}public long decrease() {return --cnt;} }?
旁白:考慮了int的范圍限制,long的范圍更廣泛。
三階猿類(lèi)
public class Counter3 {private static long cnt=0;public synchronized long increase() {return ++cnt;}public synchronized long decrease() {return --cnt;} }?
旁白:考慮了并發(fā)環(huán)境下的執(zhí)行
四階猿類(lèi)
public class Counter4 {private static AtomicLong cnt=new AtomicLong(0);public long increase() {return cnt.getAndIncrement();}public long decrease() {return cnt.getAndDecrement();} }?
旁白:考慮了并發(fā)環(huán)境下的cas性能更優(yōu)
五階猿類(lèi)
public class Counter5 {private static LongAdder cnt=new LongAdder();public long increase() {cnt.increment();return cnt.longValue();}public long decrease() {cnt.decrement();return cnt.longValue();} }?
旁白:在單線(xiàn)程下,并發(fā)問(wèn)題沒(méi)有暴露,兩者沒(méi)有體現(xiàn)出差距;隨著并發(fā)量加大,LongAdder 的 increment 操作更加優(yōu)秀,而 AtomicLong 的 get 操作則更加優(yōu)秀。鑒于在計(jì)數(shù)器場(chǎng)景下的特點(diǎn)—寫(xiě)多讀少,所以寫(xiě)性能更高的 LongAdder 更加適合。
六階猿類(lèi)
public class Counter6 {private static JdbcTemplateUtils jdbc=new JdbcTemplateUtils();private static long cnt=0;public long increase() {cnt=jdbc.getCnt(); return jdbc.setCnt(++cnt);}public long decrease() {cnt=jdbc.getCnt();return jdbc.setCnt(--cnt);;} }?
旁白:考慮了在集群環(huán)境下保證數(shù)據(jù)的唯一性和一致性。
七階猿類(lèi)
public class Counter7 {private static RedisclusterUtils redis=new RedisclusterUtils();private static long cnt=0;public long increase() { return redis.incr(cnt);}public long decrease() {return redis.decr(cnt);;} }?
旁白:考慮了計(jì)數(shù)器集群下的并發(fā)性能問(wèn)題,同樣的實(shí)現(xiàn)可以使用zk或者mongo等內(nèi)存數(shù)據(jù)庫(kù)。
八階猿類(lèi)
public class Counter8 {private static JdbcTempalteUtils jdbc=new JdbcTempalteUtils();private static RedisclusterUtils redis=new RedisclusterUtils();private static long cnt=0;public long increase() { if(redis.exsits(cnt)) {return redis.incr(cnt);}cnt=jdbc.getCnt(key);++cnt;redis.set(key,cnt);return cnt;}public long decrease() {if(redis.exsits(cnt)) {return redis.decr(cnt);}cnt=jdbc.getCnt(key);--cnt;redis.set(key,cnt);return cnt;} }?
旁白:考慮到redis宕機(jī)或者不可用的情況下的處理,有備份方案。
九階猿類(lèi)
這個(gè)要免考的。
?
參考資料:
【1】https://mp.weixin.qq.com/s/yAvJFZWxfKb38IDMjQd5zg
轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/11550965.html
總結(jié)
以上是生活随笔為你收集整理的花果山第一届猿类分级考试实录--Talk is cheap,Show me the code的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 猿类如何捕获少女心--难以琢磨的try-
- 下一篇: 消灭 Java 代码的“坏味道”【转】