Difference between Atomic set and volatile set in Java?

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?

+4
source share
3 answers

. , . . . , , int, , reset () .

: java?

+1

, . volatile java.util.concurrent.atomic , , , . volatile , , - , .

+1

. .

Foo: . , ++, . ++ i = i + 1, , .

: , -. , compareAndSet inc, . , ? AtomicXXX , , , .

, :

private final AtomicInteger x = new AtomicInteger(0);
private final AtomicBoolean istrue = new AtomicBoolean(false);
+1

All Articles