-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSystemMain.java
More file actions
241 lines (206 loc) · 7.7 KB
/
FileSystemMain.java
File metadata and controls
241 lines (206 loc) · 7.7 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* ==========================================
* 1. THE COMPOSITE BASE: FileSystemNode
* ==========================================
*/
abstract class FileSystemNode {
protected String name;
protected Directory parent;
protected long creationTime;
public FileSystemNode(String name, Directory parent) {
this.name = name;
this.parent = parent;
this.creationTime = System.currentTimeMillis();
}
public abstract int getSize();
public abstract boolean isDirectory();
public String getName() { return name; }
}
/**
* ==========================================
* 2. THE LEAF: File
* ==========================================
*/
class File extends FileSystemNode {
private StringBuilder content;
/* INTERVIEW SCRIPT: "In a real OS, this lock would be inside an Inode.
Here, it protects the file content during concurrent writes." */
private final ReentrantReadWriteLock fileLock = new ReentrantReadWriteLock();
public File(String name, Directory parent) {
super(name, parent);
this.content = new StringBuilder();
}
public void write(String data) {
fileLock.writeLock().lock();
try {
this.content.append(data);
} finally {
fileLock.writeLock().unlock();
}
}
public String read() {
fileLock.readLock().lock();
try {
return content.toString();
} finally {
fileLock.readLock().unlock();
}
}
@Override
public int getSize() {
fileLock.readLock().lock();
try { return content.length(); }
finally { fileLock.readLock().unlock(); }
}
@Override
public boolean isDirectory() { return false; }
}
/**
* ==========================================
* 3. THE COMPOSITE: Directory
* ==========================================
*/
class Directory extends FileSystemNode {
// Map handles O(1) lookup and ensures unique filenames per folder
private final Map<String, FileSystemNode> children = new HashMap<>();
/* INTERVIEW EXPLANATION: Lock Striping allows high concurrency.
Multiple threads can READ different folders at once. */
private final ReentrantReadWriteLock dirLock = new ReentrantReadWriteLock();
public Directory(String name, Directory parent) {
super(name, parent);
}
public void addNode(FileSystemNode node) {
dirLock.writeLock().lock();
try {
children.put(node.getName(), node);
} finally {
dirLock.writeLock().unlock();
}
}
public FileSystemNode getChild(String name) {
dirLock.readLock().lock();
try {
return children.get(name);
} finally {
dirLock.readLock().unlock();
}
}
public List<String> ls() {
dirLock.readLock().lock();
try {
return new ArrayList<>(children.keySet());
} finally {
dirLock.readLock().unlock();
}
}
@Override
public int getSize() {
dirLock.readLock().lock();
try {
/* INTERVIEW SCRIPT: "This is the core of the Composite Pattern.
The recursion happens here—summing up files and sub-directories." */
int totalSize = 0;
for (FileSystemNode child : children.values()) {
totalSize += child.getSize();
}
return totalSize;
} finally {
dirLock.readLock().unlock();
}
}
@Override
public boolean isDirectory() { return true; }
}
/**
* ==========================================
* 4. THE ORCHESTRATOR: FileSystem (Singleton)
* ==========================================
*/
class FileSystem {
private static FileSystem instance;
private final Directory root;
private FileSystem() {
this.root = new Directory("/", null);
}
public static synchronized FileSystem getInstance() {
if (instance == null) instance = new FileSystem();
return instance;
}
/* INTERVIEW SCRIPT: "Path resolution is the bridge between human strings
and our object-oriented tree. I use a tokenizer to walk the nodes." */
public Directory resolvePath(String path) {
if (path == null || path.equals("/") || path.isEmpty()) return root;
String[] parts = path.split("/");
Directory current = root;
for (String part : parts) {
if (part.isEmpty()) continue;
FileSystemNode next = current.getChild(part);
if (next != null && next.isDirectory()) {
current = (Directory) next;
} else {
return null; // Path invalid
}
}
return current;
}
public void mkdir(String parentPath, String name) {
Directory parent = resolvePath(parentPath);
if (parent != null) {
parent.addNode(new Directory(name, parent));
}
}
public void createFile(String parentPath, String name, String initialContent) {
Directory parent = resolvePath(parentPath);
if (parent != null) {
File newFile = new File(name, parent);
newFile.write(initialContent);
parent.addNode(newFile);
}
}
}
/**
* ==========================================
* 5. THE MASTER SIMULATION
* ==========================================
*/
public class FileSystemMain {
public static void main(String[] args) throws InterruptedException {
FileSystem fs = FileSystem.getInstance();
System.out.println("--- PHASE 1: HIERARCHY SETUP ---");
fs.mkdir("/", "users");
fs.mkdir("/users", "rishi");
fs.mkdir("/users/rishi", "projects");
fs.mkdir("/users/rishi", "notes");
System.out.println("[INFO] Created structure: /users/rishi/[projects, notes]");
System.out.println("\n--- PHASE 2: CONCURRENT FILE CREATION ---");
/* INTERVIEW POINT: We use 3 threads writing to DIFFERENT folders.
Because we used Lock Striping, there is ZERO contention here. */
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> fs.createFile("/users/rishi/projects", "LLD_Code.java", "public class Main {}")); // 20 bytes
executor.submit(() -> fs.createFile("/users/rishi/notes", "todo.txt", "Buy milk, Learn LLD")); // 20 bytes
executor.submit(() -> {
Directory root = fs.resolvePath("/");
fs.createFile("/", "system_log.log", "System Booted Successfully"); // 26 bytes
});
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("\n--- PHASE 3: COMPOSITE SIZE CALCULATION ---");
/* INTERVIEW POINT: Size of /users/rishi should be projects (20) + notes (20) = 40.
The recursion automatically handles the depth. */
Directory rishiDir = fs.resolvePath("/users/rishi");
Directory rootDir = fs.resolvePath("/");
System.out.println("Size of /users/rishi: " + rishiDir.getSize() + " bytes");
System.out.println("Total System Size (/): " + rootDir.getSize() + " bytes");
System.out.println("\n--- PHASE 4: PATH SEARCH & CONTENT READ ---");
Directory projectDir = fs.resolvePath("/users/rishi/projects");
if (projectDir != null) {
File javaFile = (File) projectDir.getChild("LLD_Code.java");
System.out.println("Reading 'LLD_Code.java': " + javaFile.read());
}
System.out.println("\n--- PHASE 5: DIRECTORY LISTING (ls) ---");
System.out.println("Contents of /users/rishi: " + rishiDir.ls());
}
}