자바의 HashMap은 어떻게 구현되어 있나?
HashMap 구조도
HashMap 클래스에는 버킷이라고 불리는 배열이 존제하고, 해당 버킷에 노드가 들어가는 형식이 된다. 이 노드는 연결리스트로 구현되어 있지만 노드가 일정 개수(기본:8)이상이 되면 tree 노드로 변환된다
HashMap의 put()
기본적으로 구현된 코드는 아래와 같다. 먼저 key 오브젝트의 hascode를 호출해서 버켓 배열의 인덱스를 정하게 된다. 그 후 해당 버켓에 노드가 없으면 지금의 key, value로 하는 노드를 생성해서 배열에 저장해준다. 만약 노드가 있다면 hashcode와 equals함수를 통해서 값 비교를 진행하고 완전 일치하는 값이 없을 경우에만 링크리스트 마지막에 노드를 넣어준다
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
HashMap의 get()
get의 경우도 put함수의 동작 방식과 비슷하다. 먼저 key 객체의 hascode함수를 호출해 어느 버켓을 탐색할지 정한 후 해당 버켓으로 접근해서 equals와 hashcode가 완전히 일치하는 Value객체를 반환한다. 찾을 수가 없다면 Null을 넘겨주게 된다.
/**
* Implements Map.get and related methods.
*
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & (hash = hash(key))]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
hashcode와 equals의 중요성
이 글을 읽어보자. 중요한 점은 둘 다 재정의 하지 않는다면 hashmap은 제대로 동작할 수 없다는 점이다.
2024.05.27 - [개발/Java] - Java에서 equals와 hashCode 메서드를 재정의해야 하는 이유
ConcurrentHashMap의 동작방식
기본적인 동작 방식은 HashMap과 유사하지만, 다른 점은 object를 put 할 때 버켓에 노드가 존제할 때만 lock을 걸기 때문에 여러 쓰레드가 다른 버켓에 접근하는 경우에는 동시에 write가 가능해진다.
아래의 코드가 해당 동작 방식을 설명한다
else if (onlyIfAbsent // check first node without acquiring lock
&& fh == hash
&& ((fk = f.key) == key || (fk != null && key.equals(fk)))
&& (fv = f.val) != null)
return fv;
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key, value);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
else if (f instanceof ReservationNode)
throw new IllegalStateException("Recursive update");
}
}
깊게 생각해보기
1. 항상 성능을 O(1)으로 고정할 수 있나? 자료구조의 정확성은 고려하지 않는다.
모든 객체가 같은 hashcode와 equals를 반환한다면 hashmap에는 하나의 객체만 존제할 수 있다. 따라서 성능이 O(1)으로 보장할 수 있다.
2. 어떻게 하면 성능을 최악이 되게 동작하도록 만들 수 있냐?
hashcode를 재정의하여 항상 같은 같을 return하도록 만든다면 같은 버켓에만 value가 저장되기 때문에 성능이 최악이 되게 동작시킬 수 있다.
3. 적절하게 버킷에 들어가기 위해선 hashcode를 어떻게 오버라이딩 해야하나?
편집기에서 적용해준다.
3. key, value중 어떤 객체의 hashcode와 equal를 재정의 해야하냐?
key를 저장해야 한다. 그 이유는 key가 같은 것을 찾고, value를 return하는 방식이기 때문이다. 잘 이해가 안가면 get함수와 put함수의 동작을 다시 확인해보는 것을 추천한다.