Skip to content

Commit

Permalink
NotNegativeLong
Browse files Browse the repository at this point in the history
  • Loading branch information
nytta committed Nov 20, 2018
1 parent e298683 commit 7071be1
Showing 1 changed file with 30 additions and 13 deletions.
43 changes: 30 additions & 13 deletions cobia-core/src/main/java/lam/cobia/core/NotNegativeLong.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,37 +20,54 @@ public NotNegativeLong() {
}

public NotNegativeLong(long initialValue) {
checkValue(initialValue, 0);
value = new AtomicLong(initialValue);
}

private void checkValue(long value, long leastValue) {
if (value < leastValue) {
throw new IllegalStateException(value + " < " + leastValue);
if (initialValue < 0) {
throw new IllegalArgumentException("initialValue(" + initialValue + ") < 0");
}
value = new AtomicLong(initialValue);
}

public long getAndIncrement() {
return value.getAndIncrement();
long oldValue = value.get();
long newValue = oldValue == Long.MAX_VALUE ? 0 : oldValue + 1;
while (!value.compareAndSet(oldValue, newValue)) {
oldValue = value.get();
newValue = oldValue == Long.MAX_VALUE ? 0 : oldValue + 1;
}
return oldValue;
}

public long incrementAndGet() {
return value.incrementAndGet();
long oldValue = value.get();
long newValue = oldValue == Long.MAX_VALUE ? 0 : oldValue + 1;
while (!value.compareAndSet(oldValue, newValue)) {
oldValue = value.get();
newValue = oldValue == Long.MAX_VALUE ? 0 : oldValue + 1;
}
return newValue;
}

public long getAndDecrement() {
long oldValue = value.getAndDecrement();
checkValue(oldValue, 1);
long oldValue = value.get();
long newValue = oldValue == 0 ? 0 : oldValue - 1;
while (!value.compareAndSet(oldValue, newValue)) {
oldValue = value.get();
newValue = oldValue == 0 ? 0 : oldValue - 1;
}
return oldValue;
}

public long decrementAndGet() {
long newValue = value.decrementAndGet();
checkValue(newValue, 0);
long oldValue = value.get();
long newValue = oldValue == 0 ? 0 : oldValue - 1;
while (!value.compareAndSet(oldValue, newValue)) {
oldValue = value.get();
newValue = oldValue == 0 ? 0 : oldValue - 1;
}
return newValue;
}

public long get() {
return value.get();
}

}

0 comments on commit 7071be1

Please sign in to comment.