Java并发编程常识
写中间件经常要做两件事:
1. 延迟加载,在内存缓存已加载项。
2. 统计调用次数,拦截并发量。
就这么个小功能,团队里的人十有八九写错。
所以写了个《Java并发编程常识》的PPT,普及下,见附件。
Java并发编程常识.pptx 用LongAdder直接比下面这个行代码简洁,为什么要这样写?for (;;) {int current = get();int next = current + 1;if (compareAndSet(current, next))return next;}ConcurrentMap cache = new ConcurrentHashMap();item = cache.get(key);if (item == null) { item = new Item(); oldItem = cache.putIfAbsent(key, item); if (oldItem != null) { item = oldItem; }}value = item.get();if (value == null) {synchronized(item) { value = item.get(); if (value == null) { value = load(key); item.set(value); }}}
避免锁竞争?
习惯用guava CacheBuilder