← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
You are given a code snippet that is supposed to implement a simple in-memory cache that lazily loads values on the first request for a given key. The cache is accessed concurrently by many threads. Review the code, identify all concurrency problems, and then rewrite the class so it is thread-safe and efficient. Specifically:
Original code to review:
`java public class DataCache { private final Map<String, Data> cache = new HashMap<>();
public Data get(String key) throws InterruptedException {
if (!cache.containsKey(key)) {
Data data = loadExpensive(key); // may throw InterruptedException
cache.put(key, data);
}
return cache.get(key);
}
private Data loadExpensive(String key) throws InterruptedException {
Thread.sleep(1000); // simulate slow I/O
return new Data(key);
}
private static class Data {
private final String key;
Data(String key) { this.key = key; }
}
} `
Submit the list of issues you found and the complete corrected source code.