Using a implementation of supplier creating and caching a large file (any Class in this case that will initialize a very large object) lazily and thread-safe.
Transcribed from the original LinkedIn image post.
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
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.Optional;
import java.util.function.Supplier;
class Day25 {
public static void main(String[] args) throws Exception {
FileLoader largeFileLoader = new FileLoader();
File largeFile = largeFileLoader
.getLargeFile()
.orElseThrow(FileNotFoundException::new);
System.out.println(largeFile.getName());
}
static class FileLoader {
private Supplier<Optional<File>> largeFile =
() -> createAndCacheFile("/home/mohibulhasan/Downloads/data.json");
public FileLoader() {
System.out.println("File Loader created");
}
public Optional<File> getLargeFile() {
return largeFile.get();
}
private synchronized Optional<File> createAndCacheFile(String path) {
class LargeFileFactory implements Supplier<Optional<File>> {
private final File largeFileInstance = new File(path);
@Override
public Optional<File> get() {
return largeFileInstance.exists()
? Optional.of(largeFileInstance) : Optional.empty();
}
}
if (!(largeFile instanceof LargeFileFactory)) {
largeFile = new LargeFileFactory();
}
return largeFile.get();
}
}
}
|
The original LinkedIn graphic is preserved below.
