Search code examples
javajava-6atomicinteger

AtomicInteger getAndUpdate to zero on Java 6


I am trying to use a counter for detecting number of unique words in a text send over HTTP methods. As I need to ensure concurrency on the value of this counter, I have changed it to AtomicInteger.

In certain cases I would like to get the current value of the counter and reset it to zero. If I understand it correctly, I must not use get() and set(0) methods separately like this, but use the getAndUpdate() method, BUT! I do not know how to implement the IntUnaryOperator for this reset and if it is even possible to do that on Java 6 server.

Thank you.

public class Server {

  static AtomicInteger counter = new AtomicInteger(0);

  static class implements HttpHandler {

    @Override
    public void handle(HttpExchange spojeni) throws IOException {
      counter.getAndUpdate(???); 
    }
  }
}

Solution

  • getAndUpdate() is basically for when you want to set the value based on some operation involving the previous value (for example, doubling the value). If the value you want to update to is always zero then getAndSet() is the more obvious choice. The getAndSet() operation is available in Java 6, so addresses your problem here.

    As you don't have the lamba based atomic update operations available before Java 8, if you wanted to achieve something similar there you would either need to handle your own synchronization or use the compareAndSet() method, potentially retrying until success.