Q56. What is a Counting Semaphore?

Ans : Java provides built in semaphore (which you can imagine a locked counter). A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.

Q57. What is a BlcokingQueue?

Ans: Lets assume you have 1000s of tasks (Runnable), you want to process it. And there is a ThreadPool of 10 threads(Consumer threads), which will process each tasks. We have a Queue (Task holder) with defined size of 100. So this queue can hold upto 100 tasks maximum at a time. Now at one end of the Queue you are keep adding the tasks (Runnable) using a Producer thread. And at other end ThreadPool consumer will dequeening tasks and processing the same. Main point here is , when Queue is full (100 tasks in a queue) , producer is blocked and cannot add more tasks to blocking queue.  If Queue is empty than consumer thread cannot de-queue any tasks and will block until new tasks is added. Queue which has this behavior is called Blocking Queue.