Knowledge Guide
HomeConcurrencyConcurrency Foundations

3. Semaphore

In this example, we focus on a shared variable named counter, which is accessed by several threads at the same time. We create 10 threads for this task. Each thread works to increase the counter value, but only 5 threads are allowed to do this at the same time. This limit of 5 is set by a semaphore. The goal is for the counter to reach a specific number, called TARGET_VALUE, which is 5000 in our case.

Here are the main points of this setup:

This demonstration shows us how useful a semaphore is in situations where you want to let multiple threads do the same task at the same time, but you also want to keep control and avoid chaos. By using a semaphore, our program lets several threads increase the counter quickly while making sure there is an upper limit on concurrency.

java
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class Solution {
    // Global shared resource
    // AtomicInteger allows multiple threads to read/write value of counter without requiring synchronization
    private static final AtomicInteger counter = new AtomicInteger(0);

    // Semaphore with a count of 5
    private static final Semaphore semaphore = new Semaphore(5);

    private static final int TARGET_VALUE = 5000;

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        Thread[] workers = new Thread[10];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Thread(Solution::worker);
            workers[i].start();
        }

        for (Thread worker : workers) {
            try {
                worker.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Thread was interrupted");
            }
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Time taken: " + (endTime - startTime) / 1000.0 + " seconds");
    }

    private static void worker() {
        while (true) {
            try {
                semaphore.acquire(); // Acquire the semaphore
                if (counter.get() >= TARGET_VALUE) {
                    break;
                }
                counter.incrementAndGet(); // Atomically increments the counter
                Thread.sleep(1); // Simulate work
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Thread was interrupted");
            } finally {
                semaphore.release(); // Release the semaphore
            }
        }
    }
}

Experiment Idea: Experiment with adjusting the semaphore count from its current setting of 5. Observe and analyze how changes in this count affect the overall time taken to complete the program's execution. Does increasing or decreasing the count make the program run faster or slower? What's the impact on performance and why?

🤖 Don't fully get this? Learn it with Claude

Stuck on 3. Semaphore? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **3. Semaphore** (Concurrency) and want to truly understand it. Explain 3. Semaphore from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **3. Semaphore** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **3. Semaphore** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **3. Semaphore** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes