-
SemaphoreStaticPL/JAVA 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
'StaticPL > JAVA' 카테고리의 다른 글
Comparable, Comparator, and Collection Sort (0) 2020.03.15 Non-blocking, Lock-free operations (0) 2020.02.27 ReentrantReadWriteLock (0) 2020.02.27 ReentrantLock, lockInterruptibly, and tryLock (0) 2020.02.27 synchronized (0) 2020.02.27