I've code:
class Counter {
private int v;
public synchronized int inc() {
v = v + 1;
return v;
}
public int get() {
return v;
}
}
What do I need minimum (for performance sake) && (please don't use concurrent package as well as other packages other than java.lang I just wanna study java basics for now) to do
- make
private volatile int v;
- make
public int synchronized get() {...
- nothing (everything is ok as is)
to make the code above thread safe?
The question Should getters and setters be synchronized? doesn't give the answer due to the ambiguity:
It is a common mistake to assume that synchronization needs to be used only when writing to shared variables; this is simply not true.
For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock.
Normally, you don't have to be so careful with primitives
So I don't figure from there out the answer in case of primitive int