Say I have the following two classes.
public class Foo { private volatile Integer x = 0; private volatile boolean istrue = false; public void setInt(int x) { this.x = x; } public void setBoolean(boolean istrue) { this.istrue = istrue; } public Integer getInt() { return x; } }
against
public class Bar { private volatile AtomicInteger x = 0; private volatile AtomicBoolean istrue = false; public void setInt(int x) { this.x.set(x); } public void setBoolean(boolean istrue) { this.istrue.set(istrue); } public Integer getInt() { return this.x.get(); } }
Suppose multiple threads can access Foo or Bar. Are both classes safe threads? what is the difference between these two classes?
. , . . . , , int, , reset () .
int
: java?
, . volatile java.util.concurrent.atomic , , , . volatile , , - , .
. .
Foo: . , ++, . ++ i = i + 1, , .
i = i + 1
: , -. , compareAndSet inc, . , ? AtomicXXX , , , .
compareAndSet
inc
, :
private final AtomicInteger x = new AtomicInteger(0); private final AtomicBoolean istrue = new AtomicBoolean(false);