PageRenderTime 157ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 96 lines | 58 code | 18 blank | 20 comment | 11 complexity | 8352c9abbf7d0bb451b51649a2d8ae8d MD5 | raw file
  1. /*
  2. * Copyright 1999-2101 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.alibaba.fastjson.util;
  17. /**
  18. * for concurrent IdentityHashMap
  19. *
  20. * @author wenshao<szujobs@hotmail.com>
  21. */
  22. @SuppressWarnings("unchecked")
  23. public class IdentityHashMap<K, V> {
  24. public static final int DEFAULT_TABLE_SIZE = 1024;
  25. private final Entry<K, V>[] buckets;
  26. private final int indexMask;
  27. public IdentityHashMap(){
  28. this(DEFAULT_TABLE_SIZE);
  29. }
  30. public IdentityHashMap(int tableSize){
  31. this.indexMask = tableSize - 1;
  32. this.buckets = new Entry[tableSize];
  33. }
  34. public final V get(K key) {
  35. final int hash = System.identityHashCode(key);
  36. final int bucket = hash & indexMask;
  37. for (Entry<K, V> entry = buckets[bucket]; entry != null; entry = entry.next) {
  38. if (key == entry.key) {
  39. return (V) entry.value;
  40. }
  41. }
  42. return null;
  43. }
  44. public boolean put(K key, V value) {
  45. final int hash = System.identityHashCode(key);
  46. final int bucket = hash & indexMask;
  47. for (Entry<K, V> entry = buckets[bucket]; entry != null; entry = entry.next) {
  48. if (key == entry.key) {
  49. entry.value = value;
  50. return true;
  51. }
  52. }
  53. Entry<K, V> entry = new Entry<K, V>(key, value, hash, buckets[bucket]);
  54. buckets[bucket] = entry; // 并发是处理时会可能导致缓存丢失,但不影响正确性
  55. return false;
  56. }
  57. public int size() {
  58. int size = 0;
  59. for (int i = 0; i < buckets.length; ++i) {
  60. for (Entry<K, V> entry = buckets[i]; entry != null; entry = entry.next) {
  61. size++;
  62. }
  63. }
  64. return size;
  65. }
  66. protected static final class Entry<K, V> {
  67. public final int hashCode;
  68. public final K key;
  69. public V value;
  70. public final Entry<K, V> next;
  71. public Entry(K key, V value, int hash, Entry<K, V> next){
  72. this.key = key;
  73. this.value = value;
  74. this.next = next;
  75. this.hashCode = hash;
  76. }
  77. }
  78. }