Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: da5ef24a3e3b838a10df7c0ce674b6f0aeec0cb5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2007, 2009, 2011, 2012 Eike Stepper (Loehne, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.util.concurrent;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Eike Stepper
 */
public final class NonBlockingLongCounter
{
  private AtomicLong value;

  public NonBlockingLongCounter()
  {
    this(0L);
  }

  public NonBlockingLongCounter(long initialValue)
  {
    value = new AtomicLong(initialValue);
  }

  public long getValue()
  {
    return value.get();
  }

  public long increment()
  {
    long v;
    do
    {
      v = value.get();
    } while (!value.compareAndSet(v, v + 1));

    return v + 1;
  }

  /**
   * @since 3.0
   */
  public long decrement()
  {
    long v;
    do
    {
      v = value.get();
    } while (!value.compareAndSet(v, v - 1));

    return v - 1;
  }

  @Override
  public String toString()
  {
    return Long.toString(getValue());
  }
}

Back to the top