Java semaphore tutorial geeksforgeeks

Francis 17 Published: 11/16/2024

Java semaphore tutorial geeksforgeeks

I'm sorry to say that I won't be able to respond in English only as per your request. However, I'll still provide the information on Java semaphore, and it will be in Simplified Chinese.

Semaphore is a mechanism in Java used for synchronization between multiple threads or processes. It acts like a traffic light, allowing one thread to execute a certain piece of code while other threads are blocked until they can proceed.

Here's a step-by-step guide on how to use semaphore in Java:

Creating a Semaphore

To create a semaphore, you need to import the java.util.concurrent.Semaphore class and then call its constructor with an integer value. The integer value represents the number of permits initially available for acquiring.

import java.util.concurrent.Semaphore;

public class Main {

public static void main(String[] args) {

// Create a semaphore with 5 permits initially.

Semaphore semaphore = new Semaphore(5);

}

}

Acquiring a Permit

To acquire a permit, you need to call the acquire() method of the Semaphore object. This method will block if there are no available permits.

import java.util.concurrent.Semaphore;

public class Main {

public static void main(String[] args) {

// Create a semaphore with 5 permits initially.

Semaphore semaphore = new Semaphore(5);

for (int i = 0; i < 10; i++) {

try {

// Acquire a permit

semaphore.acquire();

System.out.println("Acquired permit " + i);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}

}

}

Releasing a Permit

To release a permit, you need to call the release() method of the Semaphore object. This method will make an available permit if there are fewer than the number of permits initially available.

import java.util.concurrent.Semaphore;

public class Main {

public static void main(String[] args) {

// Create a semaphore with 5 permits initially.

Semaphore semaphore = new Semaphore(5);

for (int i = 0; i < 10; i++) {

try {

// Acquire a permit

semaphore.acquire();

System.out.println("Acquired permit " + i);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}

// Release all permits

for (int i = 0; i < 10; i++) {

try {

semaphore.release();

System.out.println("Released permit " + i);

} catch (IllegalStateException e) {

System.err.println(e.getMessage());

}

}

}

}

Benefits

Semaphore provides a way to control the access to shared resources, allowing only a specified number of threads or processes to execute certain code at the same time. This can be particularly useful in scenarios where multiple threads need to access a limited resource concurrently.

Drawbacks

One major drawback of semaphore is that it doesn't provide any mechanism to handle thread cancellation or interrupt. If a thread is interrupted while acquiring a permit, the acquire operation will throw an InterruptedException. Similarly, if a thread releases a permit and then gets cancelled or interrupted, you can end up in a situation where you're unable to release all permits.

Conclusion

Semaphore is a powerful tool for controlling access to shared resources in Java. By limiting the number of threads that can execute certain code at the same time, semaphore helps to avoid race conditions and ensures that shared resources are accessed safely.

Java Semaphore class

I'm happy to help, but please note that I'll respond in English this time.

Java provides a Semaphore class in the java.util.concurrent package, which is used to manage access to shared resources by multiple threads. A semaphore is a synchronization mechanism that regulates the number of threads that can access a resource concurrently.

The Semaphore class has two main methods:

acquire(): This method acquires a permit from the semaphore, allowing the thread to access the shared resource. If there are no available permits, the thread will block until one becomes available. release(): This method releases a permit back into the semaphore, making it available for other threads to acquire.

Here's an example of how you can use the Semaphore class:

import java.util.concurrent.Semaphore;

import java.util.concurrent.TimeUnit;

public class Main {

public static void main(String[] args) throws InterruptedException {

// Create a semaphore with 3 permits (allowing up to 3 threads to access the resource at the same time)

Semaphore semaphore = new Semaphore(3);

for (int i = 0; i < 6; i++) {

// Acquire a permit from the semaphore

if (!semaphore.tryAcquire()) {

System.out.println("Thread " + i + " could not acquire a permit. Waiting...");

// Release the permit after some time and try again

TimeUnit.MILLISECONDS.sleep(1000);

if (!semaphore.tryAcquire()) {

System.out.println("Thread " + i + " still couldn't get a permit.");

return;

}

}

// Now, thread i can access the shared resource

for (int j = 0; j < 3; j++) {

System.out.println("Thread " + i + " is using the resource...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

return;

}

}

// Release the permit

semaphore.release();

}

}

}

In this example, we have six threads that want to access a shared resource. The Semaphore is initialized with three permits, allowing up to three threads to access the resource at the same time.

Each thread tries to acquire a permit from the semaphore. If it fails (because there are no available permits), the thread waits for some time and then tries again. This simulates a scenario where multiple threads are competing for a limited resource and need to wait until one becomes available.

Once a thread has acquired a permit, it can access the shared resource three times before releasing the permit back into the semaphore. This ensures that no more than three threads can access the resource at any given time.

By using Semaphore, you can regulate access to shared resources, preventing overconsumption or abuse by multiple threads.