Java
ArrayBlockingQueue vs LinkedBlockingQueue
SH.DevBlog
2023. 10. 24. 23:36
Feature | ArrayBlockingQueue | LinkedBlockingQueue |
Implementation | It’s backed by an array | It uses linked nodes |
Queue Size | It’s a bounded queue. Therefore, it’s mandatory to specify the initial capacity while creating it. | It’s not mandatory to mention size. |
Fairness Policy | We can set a fairness policy in it | There’s no option to set a fairness policy in this |
Number of Locks | It uses one ReentrantLock. The same lock is used for both put and take operations. | It uses separate ReentrantLock for read and write operations. This prevents contention between producer and consumer threads. |
Memory space | Since it’s mandatory to mention initial capacity in it, we can end up allocating more space than required. | It usually doesn’t pre-allocate nodes. Therefore, its memory footprint matches its size |
알림 서비스 구축시 Thread-Safe한 메시지 큐를 구축하기 위해서 위의 둘중 고민을 하다가 LinkedBlockingQueue를 사용하였다.
가장 핵심적인 부분은 네번째 Number of Locks이다.
ArrayBlockingQueue는 ReentrantLock을 1개만 사용한다. 즉, ArrayBlockingQueue는 동시에 데이터를 읽거나 사용할 수 없다. 하지만 LinkedBlockingQueue는 동시에 데이터를 읽거나 사용할 수 있다는 큰 차이가 있다.
참조 : https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue