How to use AtomicInteger?

694 Views Asked by At

I have a class, for example:

public class A{
    private final int number;

    public A(int number){
         this.number = number;
    }
}

Quesiton is, I want to update number time by time, and I must make A object stateless, which means nubmer has to be final. My friend suggested my to use AtomicInteger class, but I don't know how to make it work.

2

There are 2 best solutions below

2
On

AtomicInteger are thread safe, you should use it like this :

public class Atomic{
  private AtomicInteger number;

  public Atomic(int number){
       this.number = new AtomicInteger(number);
  }

  public int getNumber() {
    return number.get();
  }

  public void setNumber(int number) {
    this.number.set(number);;
  }

}

But if you want to make something final you shouldn't use AtomicInteger, and final must be known at compile time so your solution is encapsulation, something like you did :

public final class Atomic{
  private int number;

  public Atomic(int number){
       this.number = number;
  }

  public int getNumber() {
    return this.number;
  }
}

For a stateless object I think you misunderstood what it means.

1
On

Having an AtomicInteger will not make the class stateless. Updating the integer, atomic or not, will change the internal state of the instance.

You could make the class immutable, i.e. state can't change, and create a new instance for each state change. Example:

public class A {
    private final int number;
    public A(int n) {
        number = n;
    }
    public int getNumber() {
        return number;
    }
    public A setNumber(int n) {
        return new A(n);
    }
}