SyntaxPilot
Courses/Low-Level Design/Lesson 26

Low-Level Design · Lesson 26 of 90 · 12 min

Prototype and Object Pool patterns

Prototype patterncloningCloneableclone()shallow copydeep copycopy constructorcopy factoryprototype registryObject Pool patternpooled objectsacquire and releaseconnection poolingwhen pooling helps

These are the notes for Low-Level Design (LLD) episode 26, the last of the creational patterns (patterns about creating objects). Both patterns answer one problem: creating an object is slow or expensive. Prototype says: set up one good object, then copy it. Object Pool says: don't throw expensive objects away, lend them out and take them back. On the way we meet Cloneable and clone(), the shallow copy bug that makes bills share one list, deep copies, copy constructors, copy factories, a prototype registry, then acquire and release, the stale state security bug, connection pooling, and when pooling helps or hurts. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real; times in milliseconds vary a little from run to run.

Part 1: Prototype

1. The real-life idea: a wedding card, designed once

At the printer In code
The designer spends hours on the original card A prototype: one fully set-up object
Photocopy it for 300 guests Cloning: copying an object instead of building it from scratch
Write each guest's name on their copy Change only the fields that differ
Each card needs its own envelope, not one shared envelope Deep copy: copies must not share changeable parts

2. The slow way: repeat the expensive setup

Creating a Bill is slow: the constructor loads the logo, fonts and tax rules. We fake that work with Thread.sleep(400), which pauses the program for 400 milliseconds (a millisecond is a thousandth of a second). System.currentTimeMillis() reads the clock in milliseconds, so the difference of two readings is the time taken.

import java.util.*;
class Bill {
    String shop, customer;
    List<String> items = new ArrayList<>();
    Bill(String shop) {
        this.shop = shop;
        try { Thread.sleep(400); } catch (InterruptedException e) { }   // loads logo, fonts, tax rules
    }
    public String toString() { return shop + " -> " + customer + " " + items; }
}
public class Main {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (String c : List.of("Asha", "Ravi", "Neha", "Kabir", "Meera")) {
            Bill b = new Bill("Priya's Kitchen");      // slow setup, every time
            b.customer = c;
            System.out.println(b);
        }
        System.out.println("5 bills took " + (System.currentTimeMillis() - start) + " ms");
    }
}
Priya's Kitchen -> Asha []
Priya's Kitchen -> Ravi []
Priya's Kitchen -> Neha []
Priya's Kitchen -> Kabir []
Priya's Kitchen -> Meera []
5 bills took 2036 ms

Five bills take over two seconds, because each one repeats exactly the same setup only to change one name. Five thousand bills would take over half an hour.

3. The fix: build one prototype and clone() it

import java.util.*;
class Bill implements Cloneable {
    String shop, customer;
    List<String> items = new ArrayList<>();
    Bill(String shop) {
        this.shop = shop;
        try { Thread.sleep(400); } catch (InterruptedException e) { }   // loads logo, fonts, tax rules
    }
    public String toString() { return shop + " -> " + customer + " " + items; }
    @Override public Bill clone() {
        try { return (Bill) super.clone(); }                     // copies every field, runs no constructor
        catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}
public class Main {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Bill prototype = new Bill("Priya's Kitchen");   // the slow setup, ONCE
        for (String c : List.of("Asha", "Ravi", "Neha", "Kabir", "Meera")) {
            Bill b = prototype.clone();                 // fast copy
            b.customer = c;
            System.out.println(b);
        }
        System.out.println("5 bills took " + (System.currentTimeMillis() - start) + " ms");
    }
}
Priya's Kitchen -> Asha []
Priya's Kitchen -> Ravi []
Priya's Kitchen -> Neha []
Priya's Kitchen -> Kabir []
Priya's Kitchen -> Meera []
5 bills took 457 ms

How it works:

  • Cloneable is a marker interface (episode 15): an interface with no methods at all, used as a label that says "objects of this class may be copied".
  • clone() is a method of java.lang.Object, the parent of every Java class. We override it (episode 8) and make it public with return type Bill (a covariant return type, episode 9).
  • super.clone() asks Object.clone() to create a new object of the same class and copy every field's value into it, without running any constructor. So the slow setup is skipped.
  • super.clone() is declared to throw CloneNotSupportedException, a checked exception (episode 5: one the compiler forces you to catch or declare). Because our class implements Cloneable it will never actually be thrown, so we wrap it in an AssertionError, an error that means "this should never happen".

Five bills now cost about one prototype, under half a second.

4. The shallow copy bug

Each customer now orders a thali, added to their bill's items list after cloning:

import java.util.*;
class Bill implements Cloneable {
    String shop, customer;
    List<String> items = new ArrayList<>();
    Bill(String shop) {
        this.shop = shop;
        try { Thread.sleep(400); } catch (InterruptedException e) { }   // loads logo, fonts, tax rules
    }
    public String toString() { return shop + " -> " + customer + " " + items; }
    @Override public Bill clone() {
        try { return (Bill) super.clone(); }                     // copies every field, runs no constructor
        catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}
public class Main {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Bill prototype = new Bill("Priya's Kitchen");   // the slow setup, ONCE
        for (String c : List.of("Asha", "Ravi", "Neha", "Kabir", "Meera")) {
            Bill b = prototype.clone();                 // fast copy
            b.customer = c;
            b.items.add(c + "'s thali");
            System.out.println(b);
        }
        System.out.println("5 bills took " + (System.currentTimeMillis() - start) + " ms");
    }
}
Priya's Kitchen -> Asha [Asha's thali]
Priya's Kitchen -> Ravi [Asha's thali, Ravi's thali]
Priya's Kitchen -> Neha [Asha's thali, Ravi's thali, Neha's thali]
Priya's Kitchen -> Kabir [Asha's thali, Ravi's thali, Neha's thali, Kabir's thali]
Priya's Kitchen -> Meera [Asha's thali, Ravi's thali, Neha's thali, Kabir's thali, Meera's thali]
5 bills took 464 ms

Every bill is charging for everyone's food. super.clone() copied each field's value. For a field like List<String> items, the value is a reference: the address of the list object in memory (episode 2). So all five copies point to the same single list. That is a shallow copy: the object is copied, but the objects it points to are shared.

Shallow copy Deep copy
Primitive fields (int, boolean) copied copied
Reference fields (List, arrays, other objects) the reference is copied: the inner object is shared the inner object is copied too
Change the copy's list the prototype and every other copy see it only that copy changes
Java's Object.clone() does this by default you write it yourself

5. The fix: a deep copy inside clone()

import java.util.*;
class Bill implements Cloneable {
    String shop, customer;
    List<String> items = new ArrayList<>();
    Bill(String shop) {
        this.shop = shop;
        try { Thread.sleep(400); } catch (InterruptedException e) { }   // loads logo, fonts, tax rules
    }
    public String toString() { return shop + " -> " + customer + " " + items; }
    @Override public Bill clone() {
        try { Bill copy = (Bill) super.clone(); copy.items = new ArrayList<>(items); return copy; }  // deep
        catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}
public class Main {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Bill prototype = new Bill("Priya's Kitchen");   // the slow setup, ONCE
        for (String c : List.of("Asha", "Ravi", "Neha", "Kabir", "Meera")) {
            Bill b = prototype.clone();                 // fast copy
            b.customer = c;
            b.items.add(c + "'s thali");
            System.out.println(b);
        }
        System.out.println("5 bills took " + (System.currentTimeMillis() - start) + " ms");
    }
}
Priya's Kitchen -> Asha [Asha's thali]
Priya's Kitchen -> Ravi [Ravi's thali]
Priya's Kitchen -> Neha [Neha's thali]
Priya's Kitchen -> Kabir [Kabir's thali]
Priya's Kitchen -> Meera [Meera's thali]
5 bills took 460 ms

After super.clone(), the copy gets its own ArrayList filled with the prototype's items (new ArrayList<>(items) copies the elements into a new list). Strings such as shop can stay shared, because a String is immutable (it can never change), so sharing it is safe. Rule: deep-copy everything that can change: lists, maps, arrays, and mutable objects.

6. Forgetting Cloneable

class Bill {                                             // forgot: implements Cloneable
    String shop = "Priya's Kitchen";
    @Override public Bill clone() {
        try { return (Bill) super.clone(); }
        catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}
public class Main {
    public static void main(String[] args) {
        Bill b = new Bill().clone();
        System.out.println(b.shop);
    }
}
Exception in thread "main" java.lang.AssertionError: java.lang.CloneNotSupportedException: Bill
    at Bill.clone(Main.java:5)
    at Main.main(Main.java:10)
Caused by: java.lang.CloneNotSupportedException: Bill
    at java.base/java.lang.Object.clone(Native Method)
    at Bill.clone(Main.java:4)
    ... 1 more

It compiles, then fails at runtime: Object.clone() checks for the Cloneable label and throws CloneNotSupportedException: Bill without it (our catch wrapped it in the AssertionError; the original is shown after Caused by:).

7. Safer Java style: copy constructor, copy factory, prototype registry

Because of these traps (a marker interface with no clone() method in it, a cast, a checked exception, shallow by default, and final fields can't be reassigned after super.clone()), many Java developers avoid clone() and write:

  • a copy constructor: a constructor that takes another object of the same class and copies its fields itself, Bill(Bill other);
  • a copy factory: a static method that returns a copy, Bill.copyOf(other).

A prototype registry is a map from a name to a ready-made prototype; to make a new object you look up a template by name and copy it.

import java.util.*;
class Bill {
    final String shop, type; String customer; final List<String> items;
    Bill(String shop, String type, List<String> items) {   // the slow, real constructor
        this.shop = shop; this.type = type; this.items = new ArrayList<>(items);
        try { Thread.sleep(400); } catch (InterruptedException e) { }
    }
    Bill(Bill other) {                                     // copy constructor: no slow setup
        shop = other.shop; type = other.type; customer = other.customer;
        items = new ArrayList<>(other.items);              // deep copy of the list
    }
    static Bill copyOf(Bill other) { return new Bill(other); }   // copy factory
    public String toString() { return type + " bill -> " + customer + " " + items; }
}
public class Main {
    static final Map<String, Bill> templates = new HashMap<>();   // the prototype registry
    public static void main(String[] args) {
        templates.put("dine-in", new Bill("Priya's Kitchen", "Dine-in", List.of("water")));
        templates.put("delivery", new Bill("Priya's Kitchen", "Delivery", List.of("packing Rs 10")));
        Bill a = Bill.copyOf(templates.get("delivery")); a.customer = "Asha"; a.items.add("thali");
        Bill r = Bill.copyOf(templates.get("dine-in"));  r.customer = "Ravi"; r.items.add("dosa");
        System.out.println(a);
        System.out.println(r);
        System.out.println("template still: " + templates.get("delivery").items);
    }
}
Delivery bill -> Asha [packing Rs 10, thali]
Dine-in bill -> Ravi [water, dosa]
template still: [packing Rs 10]

The templates are built (slowly) once; every bill after that is a cheap copy. The delivery template still has only the packing charge, so the copies never change their prototypes.

8. It has a name: the Prototype pattern

A creational pattern used when the kinds of objects to create are given by a prototypical instance, which is cloned to produce new objects. Use it when:

  • setting up an object is slow (loading files, parsing, network calls) and many similar objects are needed;
  • the objects you need are only known at runtime (a shop owner creates bill templates in the app);
  • you want new objects configured like an existing one without knowing its exact class (template.copy() works for any subclass that implements it).
Role In our code
Prototype (interface or class with a copy method) Bill with clone() / copyOf()
Concrete prototype a configured Bill, e.g. the delivery template
Prototype registry Map<String, Bill> templates
Client Main, which copies instead of calling the slow constructor

Part 2: Object Pool

9. The real-life idea: luggage trolleys at a station

At the station In code
A row of trolleys, bought once and kept ready An object pool: a set of ready objects created in advance
Take one acquire(): borrow an object
Return it; staff empty it first release(): give it back; the pool resets it
All trolleys taken: wait or carry your bag The pool has a maximum; it can be exhausted

10. The slow way: a new connection per request

A database is a separate program that stores data (Priya's orders); the app talks to it over a connection. Opening one is slow (a network handshake plus a login), faked here with 300 ms.

import java.util.*;
class Connection {
    static int opened = 0; final int id; String user;     // user = who is logged in on it
    Connection() {                                    // slow: network + login handshake
        try { Thread.sleep(300); } catch (InterruptedException e) { } id = ++opened; }
    String run(String sql) { return "conn " + id + " as " + user + ": " + sql; }
}
public class Main {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 6; i++) {
            Connection c = new Connection();       // open a new one for every request
            c.user = "user" + i;
            System.out.println(c.run("SELECT * FROM orders"));
        }
        System.out.println(Connection.opened + " opened, " + (System.currentTimeMillis() - start) + " ms");
    }
}
conn 1 as user1: SELECT * FROM orders
conn 2 as user2: SELECT * FROM orders
conn 3 as user3: SELECT * FROM orders
conn 4 as user4: SELECT * FROM orders
conn 5 as user5: SELECT * FROM orders
conn 6 as user6: SELECT * FROM orders
6 opened, 1873 ms

Six connections, almost two seconds, and most of that time is spent opening connections, not running queries.

11. A pool: acquire and release (and the stale state bug)

The Pool keeps free connections in an ArrayDeque (episode 4: pop() takes from the front, push() puts at the front) and creates at most max connections. acquire() returns a free one if there is one, otherwise creates a new one while under the limit. release() puts it back. This first version does not reset anything:

import java.util.*;
class Connection {
    static int opened = 0; final int id; String user;     // user = who is logged in on it
    Connection() {                                    // slow: network + login handshake
        try { Thread.sleep(300); } catch (InterruptedException e) { } id = ++opened; }
    String run(String sql) { return "conn " + id + " as " + user + ": " + sql; }
}
class Pool {
    private final ArrayDeque<Connection> free = new ArrayDeque<>();
    private final int max; private int created = 0;
    Pool(int max) { this.max = max; }
    Connection acquire() {                         // borrow
        if (!free.isEmpty()) return free.pop();
        if (created < max) { created++; return new Connection(); }
        throw new IllegalStateException("pool exhausted: all " + max + " connections in use");
    }
    void release(Connection c) { free.push(c); }     // give it back
}
public class Main {
    public static void main(String[] args) {
        Pool pool = new Pool(2);
        Connection a = pool.acquire(); a.user = "Asha";
        System.out.println(a.run("SELECT * FROM my_orders"));
        pool.release(a);
        Connection r = pool.acquire();              // Ravi's request, forgot to log in
        System.out.println(r.run("SELECT * FROM my_orders"));
    }
}
conn 1 as Asha: SELECT * FROM my_orders
conn 1 as Asha: SELECT * FROM my_orders

Ravi's request ran as Asha and read her orders. The pooled object still held the previous user's data. That is stale state, and here it is a security bug. Pooled objects can also carry leftover confidential data (a card number, a token) to the next borrower.

12. Reset on release

import java.util.*;
class Connection {
    static int opened = 0; final int id; String user;     // user = who is logged in on it
    Connection() {                                    // slow: network + login handshake
        try { Thread.sleep(300); } catch (InterruptedException e) { } id = ++opened; }
    String run(String sql) { return "conn " + id + " as " + user + ": " + sql; }
}
class Pool {
    private final ArrayDeque<Connection> free = new ArrayDeque<>();
    private final int max; private int created = 0;
    Pool(int max) { this.max = max; }
    Connection acquire() {                         // borrow
        if (!free.isEmpty()) return free.pop();
        if (created < max) { created++; return new Connection(); }
        throw new IllegalStateException("pool exhausted: all " + max + " connections in use");
    }
    void release(Connection c) { c.user = null; free.push(c); }     // give it back
}
public class Main {
    public static void main(String[] args) {
        Pool pool = new Pool(2); long start = System.currentTimeMillis();
        for (int i = 1; i <= 6; i++) {
            Connection c = pool.acquire(); c.user = "user" + i;
            System.out.println(c.run("SELECT * FROM orders"));
            pool.release(c);                              // back to the pool, reset
        }
        System.out.println(Connection.opened + " opened, " + (System.currentTimeMillis() - start) + " ms");
    }
}
conn 1 as user1: SELECT * FROM orders
conn 1 as user2: SELECT * FROM orders
conn 1 as user3: SELECT * FROM orders
conn 1 as user4: SELECT * FROM orders
conn 1 as user5: SELECT * FROM orders
conn 1 as user6: SELECT * FROM orders
1 opened, 367 ms

release() now sets user = null before the connection goes back. The pool resets the objects, not the callers, because callers forget. Six requests used only one connection, since each request returned it before the next began.

13. The limit: a pool can be exhausted

import java.util.*;
class Connection {
    static int opened = 0; final int id; String user;     // user = who is logged in on it
    Connection() {                                    // slow: network + login handshake
        try { Thread.sleep(300); } catch (InterruptedException e) { } id = ++opened; }
    String run(String sql) { return "conn " + id + " as " + user + ": " + sql; }
}
class Pool {
    private final ArrayDeque<Connection> free = new ArrayDeque<>();
    private final int max; private int created = 0;
    Pool(int max) { this.max = max; }
    Connection acquire() {                         // borrow
        if (!free.isEmpty()) return free.pop();
        if (created < max) { created++; return new Connection(); }
        throw new IllegalStateException("pool exhausted: all " + max + " connections in use");
    }
    void release(Connection c) { c.user = null; free.push(c); }     // give it back
}
public class Main {
    public static void main(String[] args) {
        Pool pool = new Pool(2);
        Connection x = pool.acquire(), y = pool.acquire();   // two requests at the same time
        System.out.println("x = conn " + x.id + ", y = conn " + y.id + ", x.user = " + x.user);
        Connection z = pool.acquire();                       // a third, while both are busy
    }
}
x = conn 1, y = conn 2, x.user = null
Exception in thread "main" java.lang.IllegalStateException: pool exhausted: all 2 connections in use
    at Pool.acquire(Main.java:15)
    at Main.main(Main.java:24)

Two requests at once get connections 1 and 2 (with no leftover user). A third request while both are busy gets IllegalStateException: pool exhausted. Real pools usually make the caller wait a short time (with a timeout: a maximum waiting time) before failing.

14. It has a name: the Object Pool pattern

Keep a set of initialized, expensive objects ready; clients acquire (borrow) one, use it, and release (return) it instead of destroying it. The objects inside are pooled objects.

Real examples:

  • Connection pooling: real applications keep a pool of open database connections, usually through a pooling library, instead of opening one per request.
  • Thread pools: a fixed set of worker threads reused for many tasks (ExecutorService, episode 48).
  • Socket connections, large buffers, and large graphics objects such as fonts or bitmaps.

Rules for a correct pool:

  1. Always release, even when an exception happens: put release() in a finally block (episode 5).
  2. Reset in the pool, and clear anything confidential.
  3. Thread safety: many threads share one pool at the same time, so a real pool must be synchronized or use concurrent collections (episodes 46 to 49). Our demo pool is single-threaded.
  4. Decide what happens when it is exhausted: wait with a timeout, fail fast, or grow.
import java.util.*;

class Pool {
    private final ArrayDeque<StringBuilder> free = new ArrayDeque<>(List.of(new StringBuilder(), new StringBuilder()));
    StringBuilder acquire() { if (free.isEmpty()) throw new IllegalStateException("pool exhausted"); return free.pop(); }
    void release(StringBuilder b) { b.setLength(0); free.push(b); }    // reset, then return
    int freeCount() { return free.size(); }
}
public class Main {
    public static void main(String[] args) {
        Pool pool = new Pool();
        StringBuilder b = pool.acquire();
        try {
            b.append("order 42");
            throw new RuntimeException("payment failed");                // something goes wrong mid-request
        } catch (RuntimeException e) {
            System.out.println("error: " + e.getMessage());
        } finally {
            pool.release(b);                                            // runs even after the exception
        }
        System.out.println("free after error: " + pool.freeCount() + ", reset buffer: [" + b + "]");
    }
}
error: payment failed
free after error: 2, reset buffer: []

15. When pooling helps, and when it hurts

Pool it Don't pool it
Database connections, threads, sockets Small in-memory objects: a Bill, an Order, a Point
Large buffers, fonts, bitmaps Anything new creates quickly
Creation is slow, or the number allowed is limited You'd only add reset bugs and code

For cheap objects, pooling may not be efficient and can decrease performance, and keeping many live-but-unused objects makes garbage collection (Java's automatic memory cleanup, episode 2) take longer. Modern JVMs create and collect short-lived small objects very quickly, so just use new.

Prototype vs Object Pool

Prototype Object Pool
Problem Building each object from scratch is slow Creating and destroying objects is slow or limited
Idea Copy a ready object Reuse the same objects again and again
Each user gets A new object (a copy) A borrowed object, returned afterwards
Main bug Shallow copies share inner objects Stale state; forgetting to release
Java tools Cloneable/clone(), copy constructor, copyOf() ArrayDeque/BlockingQueue, finally, thread pools

Common mistakes

Mistake Exact message / symptom Why Fix
Shallow clone() of a list field no error: items pile up across bills Copies share one list Copy the list in clone() / the copy constructor
clone() without implements Cloneable java.lang.CloneNotSupportedException: Bill (at runtime) Object.clone() checks the marker implements Cloneable, or a copy constructor
Calling clone() on a class that didn't make it public error: clone() has protected access in Object Object.clone() is protected Override it as public
Reassigning a final field after super.clone() error: cannot assign a value to final variable items final fields can only be set in a constructor Use a copy constructor
Pool doesn't reset on release no error: Ravi's request runs as Asha Stale state in a pooled object Reset inside release()
Forgetting to release IllegalStateException: pool exhausted: all 2 connections in use Borrowed objects never come back release() in finally
Using an object after releasing it no error: two requests share one connection It now belongs to someone else Drop the reference after release()
Pooling cheap objects no error: slower, buggier code new is already fast Pool only expensive objects

The two compile errors above are real:

import java.util.*;
class Bill implements Cloneable {
    final List<String> items = new ArrayList<>();
    @Override public Bill clone() {
        try { Bill c = (Bill) super.clone(); c.items = new ArrayList<>(items); return c; }
        catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}
class Plain { }
public class Main {
    public static void main(String[] args) {
        Object p = new Plain().clone();
    }
}
Main.java:5: error: cannot assign a value to final variable items
        try { Bill c = (Bill) super.clone(); c.items = new ArrayList<>(items); return c; }
                                              ^
Main.java:12: error: clone() has protected access in Object
        Object p = new Plain().clone();
                              ^
2 errors

Mini project: a ticket template registry with a pool of printers

A cinema app prints tickets. Building a ticket template is slow; there are two printers, and a printer must be returned and cleared after each ticket. Build (1) a prototype registry with "regular" and "recliner" templates (copy constructor, deep-copy the list of perks), and (2) a pool of two printers that resets the printer's buffer on release. Print three tickets.

Solution
import java.util.*;

class Ticket {
    final String seatType; final List<String> perks; String name;
    Ticket(String seatType, List<String> perks) { this.seatType = seatType; this.perks = new ArrayList<>(perks); }
    Ticket(Ticket o) { seatType = o.seatType; perks = new ArrayList<>(o.perks); name = o.name; }   // copy constructor
    public String toString() { return seatType + " for " + name + " " + perks; }
}
class Printer {
    final int id; final StringBuilder buffer = new StringBuilder();
    Printer(int id) { this.id = id; }
    String print(Ticket t) { buffer.append(t); return "printer " + id + ": " + buffer; }
}
class PrinterPool {
    private final ArrayDeque<Printer> free = new ArrayDeque<>(List.of(new Printer(1), new Printer(2)));
    Printer acquire() { if (free.isEmpty()) throw new IllegalStateException("no printer free"); return free.pop(); }
    void release(Printer p) { p.buffer.setLength(0); free.push(p); }   // reset
}
public class Main {
    public static void main(String[] args) {
        Map<String, Ticket> templates = Map.of(
            "regular", new Ticket("Regular", List.of("3D glasses")),
            "recliner", new Ticket("Recliner", List.of("3D glasses", "blanket")));
        PrinterPool pool = new PrinterPool();
        String[][] orders = {{"regular", "Asha"}, {"recliner", "Ravi"}, {"regular", "Neha"}};
        for (String[] o : orders) {
            Ticket t = new Ticket(templates.get(o[0])); t.name = o[1];
            if (o[1].equals("Ravi")) t.perks.add("popcorn");
            Printer p = pool.acquire();
            try { System.out.println(p.print(t)); } finally { pool.release(p); }
        }
        System.out.println("recliner template: " + templates.get("recliner").perks);
    }
}
printer 1: Regular for Asha [3D glasses]
printer 1: Recliner for Ravi [3D glasses, blanket, popcorn]
printer 1: Regular for Neha [3D glasses]
recliner template: [3D glasses, blanket]

Ravi's popcorn didn't leak into the template (deep copy), and each printout starts from an empty buffer (reset on release).

Practice

1. Bill gets a Map<String, Integer> extras field (extra name to price). What must clone() do?

Answer

Give the copy its own map: copy.extras = new HashMap<>(extras);. If the map's values were mutable objects you'd copy those too; Integer is immutable, so copying the map is enough.

2. Why is a String field safe to share in a shallow copy, but a StringBuilder field is not?

Answer

String is immutable, so no copy can change it. StringBuilder is mutable: copy.sb.append("x") would change the prototype's text as well.

3. Make the pool wait instead of failing. What would you need?

Answer

A blocking structure such as ArrayBlockingQueue with poll(1, TimeUnit.SECONDS): it waits up to one second for a connection to be released, and returns null (so you can throw) if none came. This is thread-safe, which a real pool needs anyway (episode 49).

4. Name three objects in a food-delivery app worth pooling and two not worth pooling.

Answer

Worth it: database connections, HTTP connections to a payment provider, worker threads. Not worth it: Order and Bill objects (cheap, short-lived, and full of per-customer data).

5. Clone vs copy constructor: give two reasons to prefer the copy constructor.

Answer

It works with final fields, needs no Cloneable, no cast and no checked exception, and the copying logic is ordinary readable code you control (including deep copies).

Quick quiz

Bill proto = new Bill("Priya's Kitchen");
Bill a = proto.clone();   // shallow clone
Bill b = proto.clone();
a.items.add("dosa");
System.out.println(b.items);

What does this print?

  • A. []
  • B. [dosa]
  • C. null
  • D. CloneNotSupportedException
Answer

B. [dosa]. A shallow clone copies the reference, so proto, a and b share one list. With a deep copy it would print [].

Interview questions

  1. What is the Prototype pattern? Creating new objects by copying an existing, fully set-up object (the prototype) instead of building them from scratch.
  2. When is it useful? When construction is expensive, when the types or configurations are only known at runtime, and to avoid a parallel hierarchy of factories.
  3. Shallow vs deep copy? Shallow copies field values, so referenced objects are shared; deep copy also copies the referenced (mutable) objects.
  4. What does Object.clone() do? Creates a new object of the same class and copies all fields (shallow) without calling a constructor; it throws CloneNotSupportedException unless the class implements Cloneable.
  5. Why do many developers avoid clone()? Cloneable has no clone() method, it's shallow by default, needs a cast and a checked exception, and doesn't work with final fields; copy constructors and copy factories are clearer.
  6. What is a prototype registry? A map of named, ready prototypes; clients ask for a copy by name.
  7. What is the Object Pool pattern? Keeping a set of initialized, expensive objects that clients acquire and release instead of creating and destroying them.
  8. Name real pools. Database connection pools, thread pools (ExecutorService), socket and buffer pools.
  9. What can go wrong with pools? Stale state or leaked data if objects aren't reset, pool exhaustion if objects aren't released, thread-safety bugs, and lower performance when pooling cheap objects.
  10. Who resets a pooled object? The pool, in release(), never the callers.

Glossary

Term Meaning, with an example
Creational patterns Patterns about creating objects: Singleton, Factory, Abstract Factory, Builder, Prototype, Object Pool
Prototype pattern Make new objects by copying a ready-made one. prototype.clone()
Prototype The fully set-up object that is copied. The delivery bill template
Cloning Copying an object instead of constructing it. Bill b = prototype.clone();
Cloneable Marker interface that allows Object.clone() to copy a class
Marker interface An interface with no methods, used as a label (episode 15)
clone() Method of Object that copies all fields without running a constructor; override it as public
super.clone() Calls Object.clone() from inside your override
CloneNotSupportedException Checked exception thrown by Object.clone() when the class isn't Cloneable
Checked exception An exception the compiler forces you to catch or declare (episode 5)
AssertionError An error meaning "this should never happen"
Reference The address of an object; a variable of a class type holds one (episode 2)
Shallow copy Copies field values; referenced objects are shared. Five bills, one list
Deep copy Also copies the referenced mutable objects. copy.items = new ArrayList<>(items)
Copy constructor A constructor that copies another object of the same class. Bill(Bill other)
Copy factory A static method that returns a copy. Bill.copyOf(other)
Prototype registry A map from a name to a ready prototype. templates.get("delivery")
Immutable Cannot change after creation; safe to share. String
Millisecond One thousandth of a second; System.currentTimeMillis() reads the clock in ms
Thread.sleep(ms) Pauses the current thread; used here to fake slow work
Object Pool pattern Keep expensive objects ready; lend them out and take them back
Pooled object An object that lives in a pool and is reused. A Connection
acquire / release Borrow an object from the pool / give it back
Stale state Leftover data from a previous user in a reused object. Ravi running as Asha
Pool exhausted Every pooled object is in use and the pool may not create more
Timeout The longest time you're willing to wait. Wait 1 second for a connection
Database A separate program that stores data (orders, users)
Connection The open link between an app and a database (or another server)
Connection pooling Keeping database connections open and reusing them across requests
Thread pool A fixed set of worker threads reused for many tasks (episode 48)
Thread-safe Works correctly when used by many threads at the same time (episodes 46-50)
finally A block that runs whether or not an exception happened; the place to release
Garbage collection Java's automatic removal of objects no longer used (episode 2)
ArrayDeque A double-ended queue; push/pop work at the front (episode 4)

Summary

  • Prototype: set up one object, then copy it. Cloneable + clone() copy fields without a constructor, but the copy is shallow: lists and other mutable objects are shared unless you deep-copy them.
  • Prefer a copy constructor or copy factory; keep named templates in a prototype registry.
  • Object Pool: keep expensive objects ready; acquire, use, release; the pool resets each object, has a limit, and must be thread-safe in real use.
  • Pool connections and threads, not cheap in-memory objects.

Next episode: The Adapter pattern.