Is it possible to do this without using synchronized? Is there, for instance, an extended AtomicInteger class with a more powerful compareAndSet?
You should be able to do that without a synchronized
block. No there isn't more extended AtomicInteger
class.
If I'm understanding you requirements, you can do this in a while
loop. Something like:
final AtomicInteger occupied = new AtomicInteger();
...
int prev;
int numResources = myTask.getResources();
do {
prev = occupied.get();
if (numResources + prev > limit) return false;
} while (!occupied.compareAndSet(prev, prev + numResources));
This loop will spin updating the occupied if possible. If it reaches the limit it will return false. You need the spin because if other threads have updated the occupied count between when you get the previous value and you go to adjust the value then you will need to loop around and get the occupied count again. This is a typical pattern.
Also, you need to use AtomicInteger
over volatile
because you are using compareAndSet
. See this question for more information:
What is the difference between using a volatile primitive over atomic variables?