I'm learning semaphore in java using the tutorial https://www.baeldung.com/java-semaphore.
The first test in the tutorial (which is below one) is working fine.
@Test
public void givenLoginQueue_whenReachLimit_thenBlocked() {
int slots = 10;
ExecutorService executorService = Executors.newFixedThreadPool(slots);
LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown();
assertEquals(0, loginQueue.availableSlots());
assertFalse(loginQueue.tryLogin());
}
If I comment the line executorService.shutdown(); in the above test case snippet then the test fails with below error.
java.lang.AssertionError: Expected :0 Actual :1 <Click to see difference> at org.testng.AssertJUnit.fail(AssertJUnit.java:59) at org.testng.AssertJUnit.failNotEquals(AssertJUnit.java:364) at org.testng.AssertJUnit.assertEquals(AssertJUnit.java:80) at org.testng.AssertJUnit.assertEquals(AssertJUnit.java:245) at org.testng.AssertJUnit.assertEquals(AssertJUnit.java:252) at LoginQueueSemaphoreTest.givenLoginQueue_whenReachLimit_thenBlocked(LoginQueueSemaphoreTest.java:24)
Once I remove the comment and enable the executorService.shutdown(); the test works fine.
I couldn't understand how the test(Semaphore available permits) depends on the external thread pool. Also, how is 1 slot available when I didn't release any permits? Any brief explanation would be helpful. Thanks in advance.