본문으로 건너뛰기
Folly Code Review · 38/89

folly::ConcurrentHashMap — sharded 동시 해시 맵

· Hawk · 4분 읽기

#한 줄 요약

folly::ConcurrentHashMap은 N개 shard로 lock 분산, Hazard Pointer로 reader-safe erase를 구현한 thread-safe hash map. AtomicHashMap의 append-only 제약을 풀어 erase/resize 둘 다 지원.

#동기

AtomicHashMap은 erase 불가, capacity 고정의 한계가 있다. 일반적인 connection pool, session table, cache는 erase가 필수다.

대안:

  • std::unordered_map + std::mutex: 전체 mutex 한 개, contention 심함.
  • shard별 mutex (예: 64 shard): contention 분산.
  • lock-free read + RCU/Hazard Pointer: erase 시 reader 안전.

folly::ConcurrentHashMap은 마지막 답. shard 단위 SharedMutex + Hazard Pointer로 erase 시점에 reader가 보고 있는 메모리 해제를 지연.

folly::ConcurrentHashMap<int, Conn> conns;
conns.insert(1, Conn{...});
conns.assign(1, Conn{...});
conns.erase(1); // reader 안전
auto it = conns.find(2); // reader는 mutex 거의 안 잡음

#API & 사용법

#include <folly/concurrency/ConcurrentHashMap.h>
folly::ConcurrentHashMap<int, std::string> m;
// 1. insert / assign
m.insert(1, "a");
m.insert_or_assign(1, "A");
// 2. find — iterator/value 반환
auto it = m.find(1);
if (it != m.end()) {
// it->second 안전하게 접근
}
// 3. erase
m.erase(1);
// 4. operator[] 없음 (없는 key에 lazy insert는 위험)
// 5. size / empty
m.size(); // approximate, atomic counter
m.empty();

finditerator를 반환. iterator가 살아 있는 동안 그 value는 안전(Hazard Pointer가 보호).

#내부 구현

#Sharding

ConcurrentHashMap shards

// 약식
template <typename K, typename V>
class ConcurrentHashMap {
static constexpr size_t kNumShards = 64;
struct alignas(64) Shard { // cache-line align
SharedMutex mutex;
// 또는 lock-free linked bucket
HashTable<K, V> table;
};
std::array<Shard, kNumShards> shards_;
};

key의 hash 상위 bit으로 shard 선택. shard 내부는 own SharedMutex.

64 shard라면 평균 contention 1/64. 64 threads 동시 random key insert도 거의 충돌 없음.

#Hazard Pointer

erase 시점에 reader가 해당 entry를 보고 있을 수 있다. 즉시 delete 하면 reader가 dangling. 해결책은 지연 해제.

  1. reader: 노드 pointer를 읽기 전 hazard pointer에 등록한다 — hazard_set(thread_local_slot, node_ptr).
  2. reader: node를 사용한다.
  3. reader: 사용이 끝나면 hazard pointer를 비운다 — hazard_set(thread_local_slot, nullptr).
  4. writer: erase 시 노드를 retired list에 추가하고, 즉시 delete하지 않는다.
  5. writer(또는 별도 reclaim thread): 주기적으로 모든 thread의 hazard pointer를 stable copy로 가져온 뒤, retired 중 어느 hazard pointer에도 없는 것만 delete한다.

folly는 folly::hazptr_* 모듈로 이 기능을 제공. ConcurrentHashMap이 내부적으로 사용.

#Insert/Find lock-acquire pattern

// 약식
std::pair<Iterator, bool> insert(K key, V value) {
size_t shard_idx = hash(key) & (kNumShards - 1);
Shard& s = shards_[shard_idx];
std::unique_lock<SharedMutex> lock(s.mutex); // writer lock
return s.table.insert(std::move(key), std::move(value));
}
Iterator find(const K& key) const {
size_t shard_idx = hash(key) & (kNumShards - 1);
const Shard& s = shards_[shard_idx];
std::shared_lock<SharedMutex> lock(s.mutex); // reader lock
auto node = s.table.find(key);
if (!node) return end();
// hazard pointer로 보호
hazptr_holder h;
h.reset(node);
return Iterator{node, std::move(h)};
}

shared_lock은 writer가 없으면 instant. shard마다 분리되어 있어 다른 shard writer가 reader를 막지 않음.

#Resize

shard별로 독립 resize. 한 shard가 grow 중에도 다른 shard는 정상 동작.

#std/abseil 비교

// std
std::unordered_map<K, V> m;
std::shared_mutex mu;
// 호출자가 lock 명시
// abseil
absl::flat_hash_map<K, V> m;
absl::Mutex mu;
// 마찬가지로 외부 lock
// folly
folly::ConcurrentHashMap<K, V> m;
// 내부에 lock 통합 — 외부 lock 불필요

abseil은 thread-safe hash map을 공개하지 않는다. 사용자가 mutex로 wrap 해야 함. folly가 ConcurrentHashMap을 제공해 통합된 API.

항목wrap된 std/abslfolly::ConcurrentHashMap
Contention단일 mutex 시 심함64 shard 분산
Erase 안전호출자 책임Hazard Pointer 보호
Reader costmutex acquire 매번shared_lock (가벼움)
API호출 시마다 lock 필요자동

#코드 리뷰 포인트

// Bad — operator[] 없는데 사용 시도
folly::ConcurrentHashMap<int, std::string> m;
m[1] = "a"; // 컴파일 에러
// Good — explicit
m.insert(1, "a");
m.insert_or_assign(1, "A");

operator[]가 의도적으로 빠진 이유: lazy insert는 reader/writer race를 만들기 쉽다. 명시적 API만.

// Bad — iterator 보관 후 mutate
auto it = m.find(1);
m.insert(2, "...");
it->second = "..."; // iterator 안전하지만 race 가능

iterator는 Hazard Pointer로 dereference 안전. 하지만 value mutation은 별개. value type이 atomic 아니면 별도 lock.

// Good — assign으로 atomic 갱신
m.assign(1, "new value"); // shard mutex 안에서 한 번에

#안티패턴

  • shard 수를 너무 작게 추정: default 64. 더 작으면 contention. 더 키울 일은 거의 없다.
  • iterator 장기 보관: Hazard Pointer slot이 점유돼 reclamation이 지연. iterator는 즉시 사용.
  • size()를 정확한 값으로 가정: shard counter 합이라 어느 순간 update 중간 값. snapshot 의도면 별도 mutex.

#정리

  • ConcurrentHashMap은 64 shard + Hazard Pointer 기반 thread-safe hash map.
  • erase, resize 모두 지원 (AtomicHashMap과 대비).
  • reader는 shared_lock + hazptr로 대부분 wait-free에 근접.
  • abseil/std는 thread-safe hash map 없음 — folly의 차별점.
  • operator[] 없음, insert/assign 명시.

#다음 편

마지막 컨테이너 EvictingCacheMap은 LRU eviction을 자동으로 한다. cache의 표준 형태.

#관련 항목

Folly Code Review · 39 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전