Skip to content

Instantly share code, notes, and snippets.

@Goom11
Last active August 29, 2015 13:57
Show Gist options
  • Save Goom11/9616761 to your computer and use it in GitHub Desktop.
Save Goom11/9616761 to your computer and use it in GitHub Desktop.
Explanation of Java BetterSorry
public final int getAndIncrement(int i) {
while (true) {
int current = get(i);
int next = current + 1;
if (compareAndSet(i, current, next))
return current;
}
}
//So this is how the AtomicIntegerArray implements getAndIncrement
//What makes it safe is that it get's the value, creates the next value
//and if during that time current has not changed, set's it to next.
//Think of compareAndSet as
public final int compareAndSet(int i, int current, int next) {
if(get(i) == current) {
set(i) = next;
}
}
//But the reason it is slow is that it can get stuck in this loop for some time
//So to limit that, we only loop "a little"
//The simplest way of doing this is what I submitted for BetterSorry
public void incVal(int i) {
while (true) {
value[i] += 1;
return;
}
}
public void decVal(int i) {
while (true) {
value[i] -= 1;
return;
}
}
public boolean swap(int i, int j) {
if (value[i] == 0) {
return false;
}
decVal(i);
incVal(j);
return true;
}
// Notice I only looped once and immediately returned
// Ideally, you would change the while true to do the same thing as getAndIncrement
// but at most loop some small number of times
// maybe 2 or 3 times
// So
public void incVal(int i) {
int current = get(i);
int next = current + 1;
if (value.compareAndSet(i, current, next))
return;
int current = get(i);
int next = current + 1;
if (value.compareAndSet(i, current, next))
return;
value[i] += 1;
}
public void decVal(int i) {
int current = get(i);
int next = current - 1;
if (value.compareAndSet(i, current, next))
return current;
int current = get(i);
int next = current - 1;
if (value.compareAndSet(i, current, next))
return current;
value[i] -= 1;
}
// This code assumes that the optimal solution is to check 2 times and the third time to just do it
// Ultimately you would repeat that code
// more times for more safety, less speed and less times for less safety, more speed
// DO NOT use a for loop because keeping track of the counter of the for loop takes time
// You would just want to past the code manually multiple times if you wanted more safety
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment