我在我的多线程代码中使用AtomicLong的incrementAndGet方法来测量我们的一些客户端代码的性能。@Overridepublicvoidrun(){longstart=System.nanoTime();attributes=client.getAttributes(columnsList);longend=System.nanoTime()-start;finalAtomicLongbefore=select.putIfAbsent(end/1000000L,newAtomicLong(1L));if(before!=null){before.incrementAnd
根据文档,AtomicInteger.incrementAndGet()是原子的。但是,在下面的源代码中,如果另一个线程在“returnnext”之前交错怎么办?那么“下一个”会不正确吗?publicfinallongincrementAndGet(){for(;;){longcurrent=get();longnext=current+1;if(compareAndSet(current,next))returnnext;}} 最佳答案 如果另一个线程交错,那么它也会成功地将值加一。原子性保证您的递增发生,并且如果两个线程尝试递增
警告:问题有点长,但分隔线以下的部分仅供好奇。Oracle的JDK7实现AtomicInteger包括以下方法:publicfinalintaddAndGet(intdelta){for(;;){intcurrent=get();intnext=current+delta;//Onlydifferenceif(compareAndSet(current,next))returnnext;}}publicfinalintincrementAndGet(){for(;;){intcurrent=get();intnext=current+1;//Onlydifferenceif(compa
当返回值不感兴趣时,AtomicInteger.getAndIncrement()之间是否有任何(甚至在实践中不相关)差异?和AtomicInteger.incrementAndGet()方法,什么时候忽略返回值?我在考虑不同之处,比如哪个更惯用,哪个会减少CPU缓存同步的负载,或者其他任何真正有助于决定哪个比扔硬币更合理使用的东西。 最佳答案 由于没有给出实际问题的答案,以下是我基于其他答案(感谢,赞成)和Java约定的个人意见:incrementAndGet()更好,因为方法名称应该以描述Action的动词开头,而这里的预期