PageRenderTime 22ms CodeModel.GetById 18ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/src/com/google/appengine/datanucleus/ConcurrentHashMapHelper.java

http://datanucleus-appengine.googlecode.com/
Java | 48 lines | 14 code | 4 blank | 30 comment | 2 complexity | 8568ce0078edef7be301cffa6dc4bcd9 MD5 | raw file
 1/**********************************************************************
 2Copyright (c) 2009 Google Inc.
 3
 4Licensed under the Apache License, Version 2.0 (the "License");
 5you may not use this file except in compliance with the License.
 6You may obtain a copy of the License at
 7
 8http://www.apache.org/licenses/LICENSE-2.0
 9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15**********************************************************************/
16package com.google.appengine.datanucleus;
17
18import java.util.concurrent.ConcurrentHashMap;
19import java.util.concurrent.atomic.AtomicInteger;
20
21/**
22 * Helper methods for manipulating a {@link ConcurrentHashMap}.
23 *
24 * @author Max Ross <maxr@google.com>
25 */
26public final class ConcurrentHashMapHelper {
27
28  /**
29   * Fetch the current value associated with the provided key, establishing a
30   * value initialized to 0 in a threadsafe way if no current value exists.
31   */
32  public static <K> AtomicInteger getCounter(ConcurrentHashMap<K, AtomicInteger> map, K key) {
33    AtomicInteger count = map.get(key);
34    if (count == null) {
35      // we don't want to overwrite a value that was added in between the
36      // fetch and the null check, so only add this value if the key is
37      // not already associated with a value.
38      map.putIfAbsent(key, new AtomicInteger(0));
39      // the result will either be the value we just put or the value that
40      // was inserted by another thread after our null-check.  Either way,
41      // we're guaranteed to have the latest.
42      count = map.get(key);
43    }
44    return count;
45  }
46
47  private ConcurrentHashMapHelper() {}
48}