我正在尝试使用计数器来检测通过HTTP方法发送的文本中唯一单词的数量。由于我需要确保此计数器值的并发性,因此我已将其更改为AtomicInteger
。
在某些情况下,我想获取计数器的当前值并将其重置为零。如果我理解正确,我一定不能像这样分别使用 get()
和 set(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(???);
}
}
}
getAndUpdate()
基本上适用于当您想根据涉及前一个值的某些操作(例如,将值加倍(来设置值时。如果要更新的值始终为零,则getAndSet()
是更明显的选择。getAndSet()
操作在 Java 6 中可用,因此请在此处解决您的问题。
由于在 Java 8 之前没有基于 lamba 的原子更新操作,如果您想在那里实现类似的东西,您需要处理自己的同步或使用 compareAndSet()
方法,可能会重试直到成功。
您可以使用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);
}`