Can I implement blocking queue using Semaphore in Java?

前端 未结 2 852
孤街浪徒
孤街浪徒 2021-01-15 15:11

I wonder if it is possible to use Semaphore to implement blocking queue?

In the below codes, I use one Semaphore to protect the critical section, and two more Semaph

2条回答
  •  时光取名叫无心
    2021-01-15 15:55

    Adding to a previous comment - we can agree your code works (it's a well known algorithm), in particular you're correct in protecting the LinkedList since it's not internally thread safe.

    However, if you compare your code to the java util implementation http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/ArrayBlockingQueue.java/?v=source it might bring up some points to consider:

    1. please Google for discussions on "ReentrantLock versus Binary Semaphore": They both create a mutex & protect a critical section, but the former better describes your intentions, plus it might be easier for future maintenance. Eg a fellow programmer can't accidentally release a ReentrantLock by a thread that didn't acquire it

    2. Google for discussions on "semaphore versus condition variable" : Both allow you to "wait for something to become available", but condition variable might be more general, plus you can tie all your conditions to a single lock (as the java util code does). I assume this has some minor effect on performance, plus the way you'll need to approach future requirements such as interrupts, timeouts, crashes. This doesn't make your code "wrong", it's just something for you to consider.

提交回复
热议问题