-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtomicCounter.java
More file actions
41 lines (32 loc) · 1.09 KB
/
Copy pathAtomicCounter.java
File metadata and controls
41 lines (32 loc) · 1.09 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
package com.diattack.emailsreceiver;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.var;
public class UsingAtomicVariables {
/*
* A Counter using AtomicInteger
*/
static class AtomicCounter {
private AtomicInteger atomicInteger = new AtomicInteger(0);
public void increment() {
atomicInteger.incrementAndGet();
}
public void decrement() {
atomicInteger.decrementAndGet();
}
public int get() {
return atomicInteger.get();
}
}
public static void main(String[] args) throws InterruptedException {
var counter = new AtomicCounter();
var cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 100_000; i++) {
cachedThreadPool.execute(() -> counter.increment());
}
cachedThreadPool.shutdown();
cachedThreadPool.awaitTermination(5000, TimeUnit.SECONDS);
System.out.println("Actual result is: " + counter.get());
}
}