I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at
If I wanted to be thread safe I'd do it this way rather than using a synchronized block.
The atomic compareAndSet achieves the same outcome as synchronized without the overhead.
AtomicInteger health = new AtomicInteger();
public void addHealth(int value)
{
int original = 0;
int newValue = 0;
do
{
original = health.get();
newValue = Math.min(100, original + value);
}
while (!health.compareAndSet(original, newValue));
}