1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.buffer.api.internal;
17
18 import io.netty5.buffer.api.MemoryManager;
19
20 import java.util.List;
21 import java.util.ServiceLoader;
22 import java.util.ServiceLoader.Provider;
23 import java.util.concurrent.atomic.AtomicReference;
24 import java.util.concurrent.locks.ReentrantLock;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27
28 public final class MemoryManagerLoader {
29
30
31
32
33
34
35
36
37 private static final AtomicReference<List<Provider<MemoryManager>>> CACHE = new AtomicReference<>();
38 private static final ReentrantLock CACHE_POP_LOCK = new ReentrantLock();
39
40 private MemoryManagerLoader() {
41 }
42
43
44
45
46 public static Stream<Provider<MemoryManager>> stream() {
47 var cachedList = CACHE.get();
48 if (cachedList != null) {
49 return cachedList.stream();
50 }
51 CACHE_POP_LOCK.lock();
52 try {
53 cachedList = CACHE.get();
54 if (cachedList != null) {
55 return cachedList.stream();
56 }
57 var loader = ServiceLoader.load(MemoryManager.class);
58 cachedList = List.copyOf(loader.stream().collect(Collectors.toList()));
59 CACHE.set(cachedList);
60 return cachedList.stream();
61 } finally {
62 CACHE_POP_LOCK.unlock();
63 }
64 }
65 }