-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphoreDemo.java
More file actions
51 lines (43 loc) · 1.45 KB
/
SemaphoreDemo.java
File metadata and controls
51 lines (43 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class SemaphoreDemo extends ConcurrentUtils {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
/*
* supports counting semaphores. Whereas locks usually grant exclusive access to variables or resources,
* a semaphore is capable of maintaining whole sets of permits.
* This is useful in different scenarios where you have to
* limit the amount concurrent access to certain parts of your application.
*/
/* can limit pool num?
* to limit 5 access to a long running task simulated by sleep():
*/
Semaphore semaphore = new Semaphore(5);
Runnable longRunningTask = () ->
{
boolean permit = false;
try {
//will timeout if semaphore not available;
//but semaphore.acquire() will block
permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
if (permit) {
System.out.println("Semaphore acquired");
sleep(5);
} else {
System.out.println("Could not acquire semaphore");
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} finally {
if (permit) {
semaphore.release();
}
}
};
IntStream.range(0, 10).forEach(i -> executor.submit(longRunningTask));
stop(executor);
}
}