WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Concurrency Β· Advanced Β· question 52 of 100

Can you explain what the Java Semaphore class is used for and how it works?

πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

In Java, a Semaphore is a synchronization primitive that allows controlling access to a limited number of resources. It is essentially a counter that is initialized with a specific value and decremented when a resource is acquired, and incremented when it is released. If the counter is zero, then any thread trying to acquire a resource is blocked until another thread releases one.

The Semaphore class in Java provides two main methods: acquire() and release(). The acquire() method is used to acquire a permit, which decrements the counter, and the release() method is used to release a permit, which increments the counter. These methods can be used in a synchronized block or method to ensure that only one thread at a time can modify the semaphore.

Here’s an example of how to use Semaphore in Java:

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2); 
        // create a semaphore with 2 permits
        Runnable task = () -> {
            try {
                semaphore.acquire(); // acquire a permit
                System.out.println(Thread.currentThread().getName() 
                    + " acquired a permit");
                Thread.sleep(1000); // simulate some work
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release(); // release a permit
                System.out.println(Thread.currentThread().getName() 
                    + " released a permit");
            }
        };
        new Thread(task, "Thread 1").start();
        new Thread(task, "Thread 2").start();
        new Thread(task, "Thread 3").start();
        new Thread(task, "Thread 4").start();
    }
}

In this example, we create a Semaphore with two permits and define a task that acquires a permit, does some work for one second, and then releases the permit. We then create four threads that execute this task. Since the semaphore has only two permits, only two threads can acquire a permit at a time. The output of the program might look something like this:

Thread 1 acquired a permit
Thread 2 acquired a permit
Thread 2 released a permit
Thread 1 released a permit
Thread 3 acquired a permit
Thread 4 acquired a permit
Thread 4 released a permit
Thread 3 released a permit

As you can see, only two threads acquire a permit at a time, and the other threads are blocked until a permit is released. This can be useful in scenarios where you want to limit the number of concurrent accesses to a resource, such as a database connection pool or a shared resource with a limited capacity.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Concurrency interview β€” then scores it.
πŸ“ž Practice Java Concurrency β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

All 100 Java Concurrency questions Β· All topics