-
[spring/java] hashmap, ConcurrnetHashMap, HashTable의 차이spring 2023. 3. 21. 16:44
강의에서 hashmap 대신 concurrentHashmap을 사용하는 것을 권장하기에 관련 내용을 찾아보게 되었다.
1. HashMap
- 사용 방법
HashMap<type, type> 변수명 = new HashMap<type, type>(); Collections.synchornizedMap(HashMap) // 동기화를 할 수 있도록 변경시킬 수 있음
- 특징
▶ 동기화되지 않으므로 스레드로부터 안전하지 않다.(synchornizedMap를 이용하여 동기화 할 수 있다.)
▶ 단일 스레드에 유리하다.
▶ 응용 프로그램의 CPU 사용량이 급증할 가능성이 높다.
▶ 속도가 빠르다.
▶ 메모리 누수나 원치않은 데이터가 조회되는 문제가 발생할 수 있다.
2. ConcurrnetHashMap
- 사용 방법
Map<K,V> map = new ConcurrentHashMap<K,V>();
- 특징
▶ 성능 저하없이 스레드로부터 안전한 구현이 가능하다.
▶ key, value에 null을 허용하지 않는다.
▶ 동시 읽기 및 쓰기 액세스에 최적화되어 있어 고성능 멀티스레드 애플리케이션에 적합하다.
▶ 동기화 시, Map 전체에 동기화 락을 걸지 않고, Map을 쪼개어 락을 건다.
3. HashTable
- 사용 방법
Hashtable<type, type> 변수명 = new Hashtable<type, type>();
- 특징
▶ 스레드로부터 가장 안전하다.
▶ hashmap과 동일한 프로그램을 돌리는 경우 속도가 약 18배 느리다.
▶ 메소드 호출 전에 스레드 간 동기화 락을 건다.
※ 동기화(Synchronization) : 스레드 간 간섭이 생기는 것을 막는 것
※ 락(Lock) : 동기화 시 객체에 대한 lock을 얻고, 종료 시 lock을 반환한다.
4. 결론
트래픽이 적은 서비스의 경우 hashmap을 사용해도되나(속도가 빠르므로)
멀티 스레드에서는 ConcurrnetHashMap로 미연에 문제점을 방지하는 것이 가장 좋다.[참고 자료]
Java Hashtable, HashMap, ConcurrentHashMap – Performance impact
There are a good number of articles that articulate functional differences between HashMap, HashTable and ConcurrentHashMap. This post compares the performance behavior of these data structures throug...
forums.oracle.com
https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/
Java 8 Concurrency Tutorial: Synchronization and Locks - winterbe
Welcome to the second part of my Java 8 Concurrency Tutorial out of a series of guides teaching multi-threaded programming in Java 8 with easily understood code examples. In the next 15 min you learn how to synchronize access to mutable shared variables vi
winterbe.com
'spring' 카테고리의 다른 글
[spring] spring과 mysql 연결 (0) 2023.05.08 [spring] 프록시 (Proxy) 패턴 (0) 2023.05.02 [spring] MyBatis와 Hibernate의 차이 (0) 2023.03.28 [spring] IntelliJ Cannot resolve symbol 'persistence' (1) 2023.03.27 [spring] GDSC spring study 2주차 오답노트 (0) 2023.03.21