-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadLocalExample.java
More file actions
44 lines (37 loc) · 1.29 KB
/
ThreadLocalExample.java
File metadata and controls
44 lines (37 loc) · 1.29 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
/*
* Copyright (c) Romanov Alexey, 2024
*/
package ru.romanow.memory.leaks;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Executors;
import static ru.romanow.memory.leaks.utils.ExampleSupport.logMemory;
import static ru.romanow.memory.leaks.utils.ExampleSupport.randomString;
public class ThreadLocalExample {
public static void main(String[] args) {
logMemory();
final var scanner = new Scanner(System.in);
final var threadLocal = ThreadLocal.<List<String>>withInitial(ArrayList::new);
final var executionService = Executors.newFixedThreadPool(10);
while (true) {
for (int i = 0; i < 10; i++) {
executionService.execute(new Generator(threadLocal, 100));
}
logMemory();
System.out.println("Continue? (Ctrl+C for exit)");
scanner.nextLine();
}
}
private record Generator(ThreadLocal<List<String>> threadLocal, int size)
implements Runnable {
@Override
public void run() {
List<String> strings = threadLocal.get();
for (int i = 0; i < size; i++) {
strings.add(randomString(32));
}
threadLocal.set(strings);
}
}
}