0

我正在尝试使用计数器来检测通过 HTTP 方法发送的文本中唯一单词的数量。由于我需要确保此计数器值的并发性,我已将其更改为AtomicInteger.

在某些情况下,我想获取计数器的当前值并将其重置为零。如果我理解正确的话,我一定不能像这样单独使用get()andset(0)方法,而是使用 getAndUpdate() 方法,但是!我不知道如何为此重置实现 IntUnaryOperator,甚至不知道是否可以在 Java 6 服务器上执行此操作。

谢谢你。

public class Server {

  static AtomicInteger counter = new AtomicInteger(0);

  static class implements HttpHandler {

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

2 回答 2

2

getAndUpdate()基本上是用于当您想要基于一些涉及先前值的操作(例如,将值加倍)设置值时。如果您要更新的值始终为零,那么getAndSet()是更明显的选择。该getAndSet()操作在 Java 6 中可用,因此请在此处解决您的问题。

由于您在 Java 8 之前没有可用的基于 Lamba 的原子更新操作,因此如果您想在那里实现类似的东西,您需要处理自己的同步或使用该compareAndSet()方法,可能会重试直到成功。

于 2017-05-25T15:47:59.513 回答
1

你可以使用getAndSet(int newValue)方法

/**
     * Atomically sets to the given value and returns the old value.
     *
     * @param newValue the new value
     * @return the previous value
     */
    public final int getAndSet(int newValue) {
        for (;;) {
            int current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }

或者您可以使用compareAndSet(int expect, int update)与初始值相关的并且您想更新新值

/**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }`
于 2017-05-25T15:43:40.557 回答