Reputation: 6374
say I have the following class
public class Hello {
private int first = 0;
private String result = "";
private Queue<Integer> queue1 = new Queue<>();
private Queue<Integer> queue2 = new ConcurrentLinkedQueue<>();
public int getFirst() {
return first;
}
public void setFirst(int first) {
this.first = first;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.first = first;
}
public void addQueue1(int number) {
queue1.add(number);
}
public void addQueue12(int number) {
queue2.add(number);
}
}
Now assume multiple threads want to modify an instance of this class. is there a way to I can turn this whole class Atomic instead of using synchornized keyword? other words multiple threads can call any getter or setter but the instance needs to be modified atomically? How can I possible use AtomicReference and change this into a thread safe class?
Upvotes: 1
Views: 71
Reputation: 43456
A class cannot be atomic; only actions can be atomic.
There's no way to say "all actions on this class have to be atomic," because that's too ill-defined. You need a way of saying "these bunch of gets and sets form one atom, but these other bunch form another atom." The way to define that is via synchronized
blocks — that's exactly what they're there for.
Upvotes: 1