Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Semaphore for Concurrent Resource Access Control

Tech 2

Semaphore is a synchronization mechanism in multithreaded programming that regulates access to shared resources by limiting the number of concurrent threads. Unlike locks such as ReentrantLock or synchronized blocks, it does not enforce mutual exclusion but shares similarities in menaging resource access through a counter-based system.

A Semaphore maintains a permit counter. Threads call acquire() to obtain a permit; if the counter is zero, the thread blocks until another thread releases a permit via release(), which increments the counter and allows more threads to proceed.

Key APIs

Constructors

  • permits: Specifies the number of available permits (resource slots).
  • fair: If set to true, ensures that waiting threads are served in FIFO order, prioritizing the longest-waiting thread.

Common Methods

  • acquire(): Blocks the calling thread until a permit is available, then acquires it.
  • tryAcquire(): Attempts to acquire a permit without blocking; returns false immediately if no permit is available.
  • release(): Releases a permit, increasing the counter and potentially unblocking waiting threads.

Example 1: Limiting access to two threads out of ten, with blocking behavior

public class ResourceController {
    public static void main(String[] args) throws InterruptedException {
        Semaphore accessControl = new Semaphore(2);
        for (int idx = 0; idx < 10; idx++) {
            new Thread(() -> {
                try {
                    accessControl.acquire();
                    System.out.println(Thread.currentThread().getName() + " is processing");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    accessControl.release();
                }
            }, "Worker-" + idx).start();
        }
    }
}

Example 2: Non-blocking access attempt with error handling for unavailable permits

public class NonBlockingAccess {
    public static void main(String[] args) throws InterruptedException {
        Semaphore resourceSemaphore = new Semaphore(2);
        for (int j = 0; j < 10; j++) {
            new Thread(() -> {
                if (resourceSemaphore.tryAcquire()) {
                    try {
                        System.out.println(Thread.currentThread().getName() + " executing task");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        resourceSemaphore.release();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + " cannot proceed");
                }
            }, "Task-" + j).start();
        }
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.