LearnFrenzy
Sign in Take a free test

Serialization · Serialization Programs · Question 6

User session with a transient cache in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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);
    }
}

Output Verified by compiling and running

[Keyboard, Mouse, Keyboard, Monitor] lookups=3
u-42 [Keyboard, Mouse, Keyboard, Monitor] lookups=6

The cache is transient, so after loading it starts empty and is rebuilt on demand (3 more lookups) – caches should never bloat the serialized data.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links