Reputation: 75
I will have multi-thread using one static variable. This variable will be updated when thread is running. Update process will be done by updateModel
function. Here is the snippet of my code
public static int total = 0;
...
run(){
// there will be calculation before update value ex: int ext = this.total/10
updateModel();
}
synchronized void updatedModel(){
this.total += 1;
}
Does updateModel need synchronized?
Upvotes: 0
Views: 125
Reputation: 18133
When I remember right, +=
isn't an atomic operation, so it can occur that one thread enters updateModel
and reads value 42
, then context switch and another thread enters updateModel
, reads value 42
, increments it to 43
, then context switch and a third thread enters updateModel
, reads value 43
, increments it to 44
, then context switch and the first thread sets the value to 43
again. So, if you want to guarantee that every thread increments the value by 1, you should synchronize it.
Upvotes: 1
Reputation: 32468
You are doing wrong here, you are using this
reference to synchronize the static variable, since the method updatedModel()
is instance. It's not thread safe anyway!
Use a static reference to synchronize a static content or make that method updatedModel()
static
Upvotes: 4
Reputation: 121998
I will have multi-thread using one static variable.
Yes , that variable needs to be synchronized and good sign to use AtomicInteger.
Keep that method as it is. make variable thread safe.
Upvotes: 3