Reputation: 1742
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;
Upvotes: 8
Views: 18056
Reputation: 109079
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++;
}
}
Upvotes: 26
Reputation: 3687
I do not think this is thread safe since the static variable is public and can be accessed by other threads in a non-thread safe manner. In order to be thread safe you must declare the variable as follows:
public static volatile int value;
Now value
being volatile, will be accessed in a synchronized block.
Upvotes: -1
Reputation: 19103
If you are using this method in two threads then you do need the volatile keyword. Without it, another thread may not get the most up to date value. (C#)
Upvotes: -1