From 01523e78358830d4c22ca7c866df4691c8331bd8 Mon Sep 17 00:00:00 2001 From: Scott Mitchell Date: Wed, 20 Jul 2016 18:58:02 -0400 Subject: [PATCH] Reduce conditionals in AbstractReferenceCounted Motivation: AbstractReferenceCounted as independent conditional statements to check the bounds of the retain IllegalReferenceCountException condition. One of the exceptions also uses the incorrect increment. Modifications: - Combined independent conditional checks into 1 where possible - Correct IllegalReferenceCountException with incorrect increment - Remove the subtract to check for overflow and re-use the addition and check for overflow to remove 1 arithmetic operation (see http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2) Result: AbstractReferenceCounted has less independent branch statements and more correct IllegalReferenceCountException. Compilation size of AbstractReferenceCounted.retain() is reduced from 58 bytes to 47 bytes. --- .../io/netty/util/AbstractReferenceCounted.java | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/common/src/main/java/io/netty/util/AbstractReferenceCounted.java b/common/src/main/java/io/netty/util/AbstractReferenceCounted.java index 20bacafa7e..ef4903c17e 100644 --- a/common/src/main/java/io/netty/util/AbstractReferenceCounted.java +++ b/common/src/main/java/io/netty/util/AbstractReferenceCounted.java @@ -53,11 +53,8 @@ public abstract class AbstractReferenceCounted implements ReferenceCounted { public ReferenceCounted retain() { for (;;) { int refCnt = this.refCnt; - if (refCnt == 0) { - throw new IllegalReferenceCountException(0, 1); - } - if (refCnt == Integer.MAX_VALUE) { - throw new IllegalReferenceCountException(Integer.MAX_VALUE, 1); + if (refCnt == 0 || refCnt == Integer.MAX_VALUE) { + throw new IllegalReferenceCountException(refCnt, 1); } if (refCntUpdater.compareAndSet(this, refCnt, refCnt + 1)) { break; @@ -73,14 +70,12 @@ public abstract class AbstractReferenceCounted implements ReferenceCounted { } for (;;) { + final int nextCnt; int refCnt = this.refCnt; - if (refCnt == 0) { - throw new IllegalReferenceCountException(0, 1); - } - if (refCnt > Integer.MAX_VALUE - increment) { + if (refCnt == 0 || (nextCnt = refCnt + increment) < 0) { throw new IllegalReferenceCountException(refCnt, increment); } - if (refCntUpdater.compareAndSet(this, refCnt, refCnt + increment)) { + if (refCntUpdater.compareAndSet(this, refCnt, nextCnt)) { break; } }