1 package org.apache.lucene.util;
3 import java.util.concurrent.atomic.AtomicLong;
6 * Licensed to the Apache Software Foundation (ASF) under one or more
7 * contributor license agreements. See the NOTICE file distributed with
8 * this work for additional information regarding copyright ownership.
9 * The ASF licenses this file to You under the Apache License, Version 2.0
10 * (the "License"); you may not use this file except in compliance with
11 * the License. You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
23 * Simple counter class
26 * @lucene.experimental
28 public abstract class Counter {
31 * Adds the given delta to the counters current value
35 * @return the counters updated value
37 public abstract long addAndGet(long delta);
40 * Returns the counters current value
42 * @return the counters current value
44 public abstract long get();
47 * Returns a new counter. The returned counter is not thread-safe.
49 public static Counter newCounter() {
50 return newCounter(false);
54 * Returns a new counter.
57 * <code>true</code> if the returned counter can be used by multiple
58 * threads concurrently.
59 * @return a new counter.
61 public static Counter newCounter(boolean threadSafe) {
62 return threadSafe ? new AtomicCounter() : new SerialCounter();
65 private final static class SerialCounter extends Counter {
66 private long count = 0;
69 public long addAndGet(long delta) {
70 return count += delta;
79 private final static class AtomicCounter extends Counter {
80 private final AtomicLong count = new AtomicLong();
83 public long addAndGet(long delta) {
84 return count.addAndGet(delta);