I have a java class as below:
public class Example implements Runnable {
private int num;
...
// Getter
public int getNum(){
return this.num;
}
// Setter
public void addToNum(int amount) {
if (this.amount> 0) {
this.num += amount;
}
}
...
}
This class can be instantiated by multiple threads. Each of this instances have its own 'num', that is, I do not want 'num' variable to be shared between all them.
To each instance, multiple threads can be accessed in concurreny in order to read/write 'num' variable. So what is the best option to protect read/write operations on 'num' variable in order to they are atomic operations?
I know that in case on C# it can be done using lock(object) like below link but in java I have no idea (I am new on it):
addToNumsynchronizedExampleinstances will not be shared between threads? Because if that is the case then you're fine and you don't need to add any synchronization or locks. Only if two (or more) threads will access the sameExampleinstance will you need to think about it.if (this.num > 0) {correct? For the given code,this.numwould never be incremented, so there is no thread safety issue :)