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