Skip to content

Instantly share code, notes, and snippets.

@iaveryanov
Created April 2, 2014 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iaveryanov/9939725 to your computer and use it in GitHub Desktop.
Save iaveryanov/9939725 to your computer and use it in GitHub Desktop.
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final long getAndAdd(long delta) {
while (true) {
long current = get();
long next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final long incrementAndGet() {
for (;;) {
long current = get();
long next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment