Java Code:
public class IncreaseTest {
public static int value = 0;
public synchronized int increment() {
return value++;
}
}
Is method increment()
thread-safe? Do I have to add the modifier keyword volatile
as follows:
public static volatile int value = 0;
Example of Non-Thread-Safe Code in Java The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.
How do we know if code is thread-safe? We can tell that code is thread-safe if it only uses and updates shared resources in a way that guarantees safe execution by multiple threads at the same time. Shared resources can be a counter variable, an array, or anything else.
The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
The increment Java operator (++) is not thread-safe.
This code is not thread-safe. The instance method will synchronize on an instance, if you have multiple instances they will not use the same monitor and therefor the updates can interleave.
You either need to remove the static from the value
field or add static to the increment()
method.
Also, as you have made value
public, there is the additional problem that value can be changed or read outside of this method without using synchronisation which could result in reading old values.
So changing your code to the following will make it thread-safe:
public class IncreaseTest {
private int value = 0;
public synchronized int increment() {
return value++;
}
}
You should probably use atomicvars
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