I was wondering if I can somehow implement an atomic tuple of 3 integers without using a synchronized block.
I guess one way would be to encode the 3 ints to an atomic long, each taking 21 bits, but that might break if the code ever requires more than 3 ints.
So what would be the java goto implementation on this case?
Make the tuple immutable, and use an AtomicReference.
public static class ThreeInts {
private final int first;
private final int second;
private final int third;
...
}
AtomicReference<ThreeInts> threeInts = new AtomicReference<>(someDefault);
and then to update, it'd be something like:
while (true) {
ThreeInts current = threeInts.get();
ThreeInts next = somehowEvaluateNew(current);
if (threeInts.compareAndSet(current, next) {
break;
}
}
You could also use just an int[] instead of the class. The downside there is that the int[] isn't immutable (and can't be made immutable). So, either you have to hide it behind some abstraction like an UnmodifiableIntArray, or you need to make it absolutely clear to all users of this code that the int[] may not be modified once it's put into the atomic reference. This obviously requires some trust on your part, so you should be careful with it; but it's an option.
If you don't mind autoboxing, you could also use a Collections.unmodifiableList(Arrays.asList(i0, i1, i2)) as a replacement for ThreeInts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With