Write a UserSession holding a user id and recently viewed product ids (saved) and a transient HashMap cache of product names that is lazily rebuilt after deserialization; show the lookup count before and after.
Solution
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class UserSession implements Serializable {
private static final long serialVersionUID = 1L;
static final Map<Integer, String> CATALOGUE = Map.of(1, "Mouse", 2, "Keyboard", 3, "Monitor");
static int lookups = 0;
final String userId;
final ArrayList<Integer> recent = new ArrayList<>();
private transient HashMap<Integer, String> cache; // not saved
UserSession(String userId) { this.userId = userId; }
String productName(int id) {
if (cache == null) cache = new HashMap<>(); // lazily (re)created
return cache.computeIfAbsent(id, k -> { lookups++; return CATALOGUE.getOrDefault(k, "?"); });
}
List<String> recentNames() { return recent.stream().map(this::productName).toList(); }
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
UserSession s = new UserSession("u-42");
s.recent.addAll(List.of(2, 1, 2, 3));
System.out.println(s.recentNames() + " lookups=" + UserSession.lookups);
UserSession back = (UserSession) load(save(s));
System.out.println(back.userId + " " + back.recentNames() + " lookups=" + UserSession.lookups);
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!