StaticPL/JAVA

Semaphore

데먕 2020. 2. 27. 15:44

1. Overview

Semaphore can be used to restrict the number of users to a particular resource or a group of resources, unlike the locks that allow only one user per resource. The semaphore can restrict any given number of users to a resource.

2. Description

2.1 How to use

Semaphore semaphore = new Semaphore(NUMBER_OF_PERMITS);
semaphore.acquire(5); // NUMBER_OF_PERMITS 

useResource();

semaphore.release(5); // NUMBER_OF_PERMITS 
Semaphore semaphore = new Semaphore(NUMBER_OF_PERMITS);
semaphore.acquire(NUMBER_OF_PERMITS); // If 0 available, Thread is blocked 

2.2 Differences between semaphore and locks

  • Semaphore doesn't have a notion of owner thread
  • Many threads can acquire a permit
  • The same thread can acquire the semaphore multiple times
  • The binary semaphore (initialized with 1) is not reentrant
  • Semaphore can be released by any thread
  • Even can be released by a thread that hasn't actually acquired it contrast with the lock which owner can only release 

2.3 Producer Consumer with Queue

Inter-thread communication for producer-consumer, using semaphore.

2.4 Usage

2.4.1 Actor Model

2.4.2 Sockets

2.4.3 Video

3. Reference

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html

https://www.geeksforgeeks.org/semaphore-in-java/