Skip to content

Commit

Permalink
Reduce conditionals in AbstractReferenceCounted
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Scottmitch committed Jul 25, 2016
1 parent d315f1b commit 01523e7
Showing 1 changed file with 5 additions and 10 deletions.
15 changes: 5 additions & 10 deletions common/src/main/java/io/netty/util/AbstractReferenceCounted.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,8 @@ protected final void setRefCnt(int refCnt) {
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;
Expand All @@ -73,14 +70,12 @@ public ReferenceCounted retain(int increment) {
}

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;
}
}
Expand Down

0 comments on commit 01523e7

Please sign in to comment.