⑤. 对象的属性修改原子类 (AtomicIntegerFieldUp dater、AtomicLongFieldUpdater、AtomicRefere nceFieldUpdater)
①. 使用目的:以一种线程安全的方式操作非线程安全对象内的某些字段
(是否可以不要锁定整个对象,减少锁定的范围,只关注长期、敏感性变化的某一个字段,而不是整个对象,已达到精确加锁+节约内存的目的)
②. 使用要求
更新的对象属性必须使用public volatile修饰符
因为对象的属性修改类型原子类都是抽象类,所以每次使用都必须使用静态方法
newUpdater( )创建一个更新器,并且需要设置想要更新的类和属性
③. 你在哪里用到了volatile
单例设置模式(双端检锁机制)
AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater
④. AtomicIntegerFieldUpdater:原子更新对象中int类型字段的值
/*** 1.从AtomicIntegerFieldUpdaterDemo代码中我们不难发现,通过AtomicIntegerFieldUpdater更新score我们获取最后的int值时相较于AtomicInteger来说不需要调用get()方法! 2.对于AtomicIntegerFieldUpdaterDemo类的AtomicIntegerFieldUpdater是static final类型也就是说即使创建了100个对象AtomicIntegerField也只存在一个不会占用对象的内存,但是AtomicInteger会创建多个AtomicInteger对象,占用的内存比AtomicIntegerFieldUpdater大, 所以对于熟悉dubbo源码的人都知道,dubbo有个实现轮询负载均衡策略的类AtomicPositiveInteger用的就是AtomicIntegerFieldUpdater。 */ @SuppressWarnings("all") public class AtomicIntegerFieldUpdaterDemo { private static final int THREAD_NUM = 1000; //设置栅栏是为了防止循环还没结束就执行main线程输出自增的变量,导致误以为线程不安全 private static CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM); Score score=new Score(); public static void main(String[] args)throws InterruptedException { Score score = new Score(); for (int j = 0; j < THREAD_NUM; j++) { new Thread(() -> { score.addTotalScore(score); countDownLatch.countDown(); }).start(); } countDownLatch.await(); System.out.println("totalScore的值:" + score.totalScore); } } class Score { String username; public volatile int totalScore = 0; //public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass,String fieldName) private static AtomicIntegerFieldUpdater atomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Score.class, "totalScore"); public void addTotalScore(Score score){ //public int incrementAndGet(T obj) { atomicIntegerFieldUpdater.incrementAndGet(score); } }
⑤. AtomicReferenceFieldUpdater:原子更新引用类型字段的值
//需求:多线程并发调用一个类的初始化方法,如果未被初始化过,将执行初始化工作,要求只能初始化一次 public class AtomicReferenceFieldUpdaterDemo { public static void main(String[] args) { MyCar myCar=new MyCar(); AtomicReferenceFieldUpdater<MyCar,Boolean>atomicReferenceFieldUpdater= AtomicReferenceFieldUpdater.newUpdater(MyCar.class,Boolean.class,"flag"); for (int i = 1; i <= 5; i++) { new Thread(()->{ if(atomicReferenceFieldUpdater.compareAndSet(myCar,Boolean.FALSE,Boolean.TRUE)){ System.out.println(Thread.currentThread().getName()+"\t"+"---init....."); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {e.printStackTrace();} System.out.println(Thread.currentThread().getName()+"\t"+"---init.....over"); }else{ System.out.println(Thread.currentThread().getName()+"\t"+"------其它线程正在初始化"); } },String.valueOf(i)).start(); } } } class MyCar{ public volatile Boolean flag=false; }
⑥. AtomicIntegerFieldUpdater与AtomicInteger使用引发的思考
通过下面代码我们不难得知使用AtomicIntegerFieldUpdater与AtomicInteger其实效果是一致的,那既然已经存在了AtomicInteger并发之神又要写一个
AtomicIntegerFieldUpdater呢?
从AtomicIntegerFieldUpdaterDemo代码中我们不难发现,通过AtomicIntegerFieldUpdater更新score我们获取最后的int值时相较于AtomicInteger来说不需要调用get()方法!
对于AtomicIntegerFieldUpdaterDemo类的AtomicIntegerFieldUpdater是static final类型也就是说即使创建了100个对象AtomicIntegerField也只存在一个不会占用对象的内存,但是AtomicInt eger会创建多个AtomicInteger对象,占用的内存比
AtomicIntegerFieldUpdater大,所以对于熟悉dubbo源码的人都知道,dubbo有个实现轮询负载均衡策略的类AtomicPositiveInteger用的就是AtomicIntegerField Update,在netty底层大量使用了这个类
public static class Candidate { int id; volatile int score = 0; AtomicInteger score2 = new AtomicInteger(); } public static final AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score"); public static AtomicInteger realScore = new AtomicInteger(0); public static void main(String[] args) throws InterruptedException { final Candidate candidate = new Candidate(); Thread[] t = new Thread[10000]; for (int i = 0; i < 10000; i++) { t[i] = new Thread() { @Override public void run() { if (Math.random() > 0.4) { candidate.score2.incrementAndGet(); scoreUpdater.incrementAndGet(candidate); realScore.incrementAndGet(); } } }; t[i].start(); } for (int i = 0; i < 10000; i++) { t[i].join(); } System.out.println("AtomicIntegerFieldUpdater Score=" + candidate.score); System.out.println("AtomicInteger Score=" + candidate.score2.get()); System.out.println("realScore=" + realScore.get()); } } /** AtomicIntegerFieldUpdater Score=5897 AtomicInteger Score=5897 realScore=5897 */
⑥. 原子操作增强类(DoubleAccumulator 、DoubleAdder 、LongAccumulator 、LongAdder)
- ①. 本小节主要讲:DoubleAccumulator 、DoubleAdder、LongAccumulator 、LongAdder
- ②. 常用API
- ③. 入门讲解(LongAdder|LongAccumulator区别)
- LongAdder只能用来计算加法、减法,且从零开始计算
- LongAccumulator提供了自定义的函数操作
public class LongAdderDemo { public static void main(String[] args) { // LongAdder只能做加减法,不能做乘除法 LongAdder longAdder=new LongAdder(); longAdder.increment(); longAdder.increment(); longAdder.increment(); longAdder.decrement(); System.out.println(longAdder.longValue()); System.out.println("========"); //LongAccumulator(LongBinaryOperator accumulatorFunction, long identity) //LongAccumulator longAccumulator=new LongAccumulator((x,y)->x+y,0); LongAccumulator longAccumulator=new LongAccumulator(new LongBinaryOperator() { @Override public long applyAsLong(long left, long right) { return left*right; } },5); longAccumulator.accumulate(1); longAccumulator.accumulate(2); longAccumulator.accumulate(3); System.out.println(longAccumulator.longValue()); } }
④. LongAdder高性能对比code演示
class ClickNumber{ int number=0; //(1). 使用synchronized实现number++ public synchronized void add_synchronized(){ number++; } //(2). 使用AtomicInteger AtomicInteger atomicInteger=new AtomicInteger(); public void add_atomicInteger(){ atomicInteger.incrementAndGet(); } //(3). 使用AtomicLong AtomicLong atomicLong=new AtomicLong(); public void add_atomicLong(){ atomicLong.incrementAndGet(); } //(4). 使用LongAdder LongAdder adder=new LongAdder(); public void add_longAdder(){ adder.increment(); } //(5). 使用LongAccumulater LongAccumulator accumulator=new LongAccumulator((x,y)->x+y,0); public void add_longAccumulater(){ accumulator.accumulate(1); } } /** * 50个线程,每个线程100w次,总点赞数出来 * */ public class LongAdderCalcDemo { // 50个线程和每个线程点在100w次 public static final int SIZE_THREAD=50; public static final int _1w=10000; public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch=new CountDownLatch(SIZE_THREAD); ClickNumber clickNumber=new ClickNumber(); long startTime = System.currentTimeMillis(); for (int i = 1 ; i <=SIZE_THREAD ; i++) { new Thread(()->{ try{ for (int j = 1; j <=10*_1w; j++) { //我们明显可以看到调用LongAdder性能最好 //clickNumber.add_synchronized(); clickNumber.add_longAdder(); } }finally { countDownLatch.countDown(); } },String.valueOf(i)).start(); } countDownLatch.await(); long endTime = System.currentTimeMillis(); System.out.println("-----consTime:"+(endTime-startTime)+"毫秒"+"\t"); System.out.println(clickNumber.adder.longValue()); } }
⑤. AtomicLong和LongAdder的分别


