# ProxyA playlist of two hundred songs stays blank for twenty seconds. Learn how a Proxy that looks exactly like the real object decides when, whether and where a call gets through, and how it differs from Decorator and Adapter.

Your music app opens a playlist of two hundred songs. And the screen stays blank for twenty
seconds. The user wanted to hear one song. So where did the time go? Every track loads its whole
audio file the moment it's created: a tenth of a second each, two hundred times over. Why load two
hundred songs to play one? There's a pattern for this, and it's called the **Proxy**.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="L1vbfU42LMw" title="Proxy" >}}

## Twenty seconds for one song

The playlist screen creates one `AudioTrack` per song, and each constructor reads the whole file.
0.1 s × 200 = 20 s before the first title shows up. Creating the real thing up front costs time the
user never asked to spend.

```mermaid {alt="The playlist screen creates two hundred AudioTrack objects; each one loads its whole audio file in the constructor, a tenth of a second each, so the screen waits twenty seconds although the user plays one song." caption="Two hundred loads before the screen appears."}
flowchart LR
  P["Playlist screen"] --> A1["new AudioTrack #1<br/>load file: 0.1 s"]
  P --> A2["new AudioTrack #2<br/>load file: 0.1 s"]
  P --> A3["… 198 more"]
  A1 --> T["20 s blank screen"]
  A2 --> T
  A3 --> T
  class P c4
  class A1,A2,A3 c1
  class T bad
```

## The director's assistant

Picture calling a busy director's office. You dial his number, and his assistant picks up. Ask for
his schedule, and she answers herself. Ask to talk to him, and she checks you're on his list first.
If he's on a plane, she takes the call and connects you when he lands. And she writes every call in
the log. The whole time, you dialed the same number. You never had to know who was screening the
call.

In code, that number is the **subject**, the interface. The director is the **real subject**. The
assistant is the **proxy**. And you, the caller, are the **client**.

```mermaid {alt="The analogy mapped onto code: the number everyone dials is the subject (the Track interface); the director is the real subject (AudioTrack); the assistant is the proxy (LazyTrack); the caller is the client (the playlist screen)." caption="Same number, someone screening the calls."}
flowchart LR
  A["the number you dial"] --> A2["subject: Track"]
  B["the director"] --> B2["real subject: AudioTrack"]
  C["the assistant"] --> C2["proxy: LazyTrack"]
  D["the caller"] --> D2["client: Playlist screen"]
  class A2 c6
  class B2 c1
  class C2 c5
  class D2 c4
```

## The obvious version: the director answers his own phone

Here's the interface. A track has a title, and it can play.

```java
public interface Track {
    String title();
    void play();
}
```

The real track, audio track, loads the whole file in its constructor. That makes play instant,
because the bytes are already there.

```java
public class AudioTrack implements Track {
    private final String title;
    private final byte[] audio;

    public AudioTrack(String title, Path file) {
        this.title = title;
        this.audio = AudioFile.load(file);   // slow
    }

    public String title() { return title; }
    public void play() { Speaker.play(audio); }
}
```

And the playlist screen builds one track for every song in the library.

```java
for (Song song : library.songs()) {
    playlist.add(new AudioTrack(song.title(), song.file()));
}
```

For a ten song album, that's fair. It's simple, and no song ever pauses when you press play.
(`AudioFile`, `Speaker`, `Song` and `library` are this example's own helpers; their bodies don't
matter here.)

## Why it breaks

But two hundred songs means two hundred loads before the screen appears. And the playlist only
needs the titles.

The tempting fix is to make the track lazy inside. Keep the file, and load it on the first play.
Fair enough. Then product asks for premium only songs, and a log of every play. Each rule lands in
the same `play` method:

```java
public void play() {
    if (!user.isPremium()) throw new SecurityException();
    if (audio == null) audio = AudioFile.load(file);
    playLog.record(title);
    Speaker.play(audio);
}
```

Look at what's left. Only the last line is about playing music. The rest decides when, who, and
what gets written down. And every screen that creates tracks now has to know about users, and about
the play log. It's the director answering his own phone, checking his own guest list, and keeping
his own call log.

```mermaid {alt="AudioTrack.play now holds four jobs: who may play (premium check), when to load (lazy load), what to record (play log), and the only line about playing; every screen that creates tracks now depends on User and PlayLog." caption="Only one line is about playing."}
flowchart LR
  P["AudioTrack.play()"] --> W1["who: premium check"]
  P --> W2["when: load on first play"]
  P --> W3["record: play log"]
  P --> W4["play the audio"]
  S["Playlist, Search, Album screens"] -. "now need" .-> U["User + PlayLog"]
  class W1,W2,W3 bad
  class W4 good
  class P c1
  class S c4
  class U bad
```

## The key idea: a stand-in that looks the same

Here's the shift. When you reach an object, whether you may, and where it lives are not that
object's job. So put them in a stand-in. It implements the same `Track` interface, and it holds the
real track, or knows how to get it. The playlist holds a `Track`, and it can't tell the difference.
The real track goes back to just playing.

The Gang of Four put it like this: *"Provide a surrogate or placeholder for another object to
control access to it."*

```mermaid {alt="Class diagram: the Playlist uses the Track interface; both AudioTrack and LazyTrack implement Track; LazyTrack holds an AudioTrack, created on demand." caption="Same interface outside; the real object behind it."}
classDiagram
  class Playlist
  class Track {
    <<interface>>
    +title() String
    +play()
  }
  class AudioTrack {
    -audio: byte[]
    +title() String
    +play()
  }
  class LazyTrack {
    -file: Path
    -real: Track
    +title() String
    +play()
  }
  Playlist --> Track : uses
  Track <|.. AudioTrack
  Track <|.. LazyTrack
  LazyTrack o--> AudioTrack : creates on demand
```

> **Look the same. Guard the way in.**

## Building the lazy proxy

Here's the lazy track. It implements `Track`, and it keeps the title, the file path, and an empty
slot for the real one. `title()` answers from its own field. No loading at all. `play()` checks the
slot. On the first call, it creates the real audio track. After that, every call goes straight to
it.

```java
public class LazyTrack implements Track {
    private final String title;
    private final Path file;
    private Track real;

    public LazyTrack(String title, Path file) {
        this.title = title;
        this.file = file;
    }

    public String title() { return title; }   // no loading

    public void play() {
        if (real == null) {
            real = new AudioTrack(title, file);
        }
        real.play();
    }
}
```

The playlist changes a single word: `LazyTrack`, instead of `AudioTrack`.

```java
playlist.add(new LazyTrack(song.title(), song.file()));
```

Now the screen opens at once, with every title. Play the third song, and only that song loads. Play
it again, and nothing loads at all.

```mermaid {alt="Sequence: the playlist asks LazyTrack for its title (answered from its own field, no loading); the first play creates the AudioTrack, which loads the file, then plays; a second play goes straight to the existing AudioTrack." caption="Load once, on the first play."}
sequenceDiagram
  participant P as Playlist
  participant L as LazyTrack
  participant A as AudioTrack
  P->>L: title()
  L-->>P: "Slow Tide" (no loading)
  P->>L: play()
  L->>A: new AudioTrack(title, file)
  Note over A: loads the file (once)
  L->>A: play()
  P->>L: play() again
  L->>A: play()
```

And `AudioTrack` didn't change at all. It still loads, and it still plays. The laziness lives in
one small class beside it.

## The kinds of proxy

The same shape does four different jobs:

| Kind | What it controls | In this lesson |
|---|---|---|
| **Virtual** proxy | creates the expensive object on demand | `LazyTrack` |
| **Protection** proxy | checks rights before passing a call on | `PremiumTrack` |
| **Remote** proxy | stands in for an object that lives somewhere else | a song on a server |
| **Smart reference** | a little housekeeping on every access: caching an answer, counting uses, logging | a play counter |

Here's a protection proxy. Premium track holds any track, and checks the user before it lets play
through.

```java
public class PremiumTrack implements Track {
    private final Track real;
    private final User user;

    public PremiumTrack(Track real, User user) {
        this.real = real;
        this.user = user;
    }

    public String title() { return real.title(); }

    public void play() {
        if (!user.isPremium()) {
            throw new SecurityException("premium only");
        }
        real.play();
    }
}
```

Each rule is its own small class now. You can test the premium check without a single audio file.
And proxies stack. Put the premium check in front of a lazy track, and a free user never loads a
single byte:

```java
Track track = new PremiumTrack(new LazyTrack(title, file), user);
```

```mermaid {alt="A free user's play call reaches PremiumTrack, which refuses it, so LazyTrack never creates the AudioTrack and no audio is loaded; a premium user's call passes through PremiumTrack and LazyTrack to the AudioTrack." caption="The outer proxy stops the call before anything loads."}
flowchart LR
  F["free user: play()"] --> P{"PremiumTrack:<br/>premium?"}
  P -->|no| X["SecurityException<br/>(never loads)"]
  P -->|yes| L["LazyTrack"] --> A["AudioTrack<br/>(loaded once)"]
  class P c4
  class L c5
  class A c1
  class X bad
```

## Proxies you already use: Hibernate and the JDK

Hibernate uses this every day. Its `getReference` method gives you a person without loading the
person. The example is straight from the Hibernate user guide:

```java
Book book = new Book();
book.setAuthor(entityManager.getReference(Person.class, personId));
```

What you get back is a proxy, generated at run time, that looks like a `Person`. Set it as the
book's author, and no query runs. Hibernate loads the row only when you use its data. And if the row
doesn't exist, the error waits until that first use. In the guide's words, "an exception will be
thrown later if the given entity does not refer to actual database state when the application
attempts to use the returned proxy in any way that requires access to its data." (Unless the entity
class is `final`, Hibernate's proxy extends the entity class, which is why the guide asks for
non-final entities.)

```mermaid {alt="Sequence: the code calls getReference and gets a Person proxy with no query; setting it as the book's author runs no query; the first call that needs its data, such as getName, makes Hibernate run the SELECT and fill in the proxy." caption="No query until you touch the data."}
sequenceDiagram
  participant C as Code
  participant H as Hibernate
  participant X as Proxy
  participant D as DB
  C->>H: getReference(id)
  H-->>C: proxy, no query
  Note over C: setAuthor(proxy)
  C->>X: getName()
  X->>D: SELECT
  D-->>X: row (or missing)
  X-->>C: name
```

The JDK can also build a proxy for any interface while your program runs. `Proxy.newProxyInstance`
takes the interfaces and one handler. Every call on that proxy goes through the handler. This one
prints the method's name, then passes the call on to the real track:

```java
Track logged = (Track) Proxy.newProxyInstance(
        Track.class.getClassLoader(),
        new Class<?>[] { Track.class },
        (proxy, method, args) -> {
            System.out.println("call: " + method.getName());
            return method.invoke(real, args);
        });
```

Calling `logged.title()` and then `logged.play()` prints `call: title` and `call: play`. The javadoc
describes it the same way: a proxy class "is a class created at runtime that implements a specified
list of interfaces", and each call "will be dispatched to the invoke method of the instance's
invocation handler". It only works for interfaces, not classes.

## The mix-up: Decorator and Adapter

Now a common mix up: a proxy is just a decorator. They do look alike. Same interface, and both
hold the real object. The difference is the purpose. A decorator adds one more job, like making
every track louder. A proxy decides when, whether, or where a call gets through.

The Gang of Four even say "a protection proxy might be implemented exactly like a decorator." So read
the intent, not the shape. The [Decorator](/patterns/decorator-pattern/) lesson puts it as
"Same interface, one more job."

An adapter is different again. It changes the interface, so the caller sees a new shape. A proxy
never does (see [Adapter](/patterns/adapter-pattern/): "Change the shape, not the job."). An
assistant who rewrites the director's answers has stopped screening the calls. She's editing them.

```mermaid {alt="Three wrappers compared: a proxy keeps the Track interface and decides who gets through; a decorator keeps the Track interface and adds one more job; an adapter turns Track into a different interface, VendorPlayer." caption="A decorator adds a job. A proxy decides who gets through."}
flowchart TB
  subgraph PX["Proxy"]
    direction LR
    P1["Track"] --> P2["Track<br/>decides who gets through"]
  end
  subgraph DC["Decorator"]
    direction LR
    D1["Track"] --> D2["Track<br/>+ one more job"]
  end
  subgraph AD["Adapter"]
    direction LR
    A1["Track"] --> A2["VendorPlayer<br/>new interface"]
  end
  PX ~~~ DC ~~~ AD
  class P2 c5
  class D2 muted
  class A2 bad
```

| | Interface | Purpose |
|---|---|---|
| Proxy | same | controls access: when, whether, where |
| Decorator | same | adds a responsibility |
| Adapter | different | makes a class fit an interface you have |
| [Facade](/patterns/facade-pattern/) | new, simpler | one front for many classes |

## When not to use it

When should you skip it? A proxy adds a level of indirection. If the object is cheap to make, you
don't need one. Lazy loading moves the delay to the first play. The list opens fast, but that first
song takes its tenth of a second. Failures show up late, too. A missing file, or a missing row,
surfaces at first use, far from where the object was made.

And the null check we wrote isn't safe across threads. Two threads can load the same song twice
(the [Singleton](/patterns/singleton-pattern/) lesson walks through the same race and its
fixes). And if the caller needs to know it's talking to a stand-in, say to show a loading spinner, a
proxy that pretends hides too much.

```mermaid {alt="Decision: is the object expensive, remote or access-controlled? If not, use it directly. Can callers live with the delay moving to first use and errors showing up late? If not, load eagerly or expose the loading state. Is it shared across threads? Then make the lazy check thread-safe. Otherwise, write the proxy." caption="The delay moves. It doesn't vanish."}
flowchart TD
  Q1{"Expensive, remote,<br/>or access-controlled?"} -->|no| A1["use the object directly"]
  Q1 -->|yes| Q2{"OK if the delay and errors<br/>move to first use?"}
  Q2 -->|no| A2["load eagerly, or show<br/>the loading state"]
  Q2 -->|yes| Q3{"Shared across threads?"}
  Q3 -->|yes| A3["make the lazy check thread-safe"]
  Q3 -->|no| A4["write the proxy"]
  A3 --> A4
  class A4 good
  class A1 muted
```

## Recap

- An object shouldn't decide when it loads, who may use it, or what gets logged.
- A proxy implements the same interface and controls the way in.
- Kinds: virtual, protection, remote, or a smart reference.
- Hibernate and the JDK make them for you.
- It's not a decorator, and it's not an adapter. And remember, the delay only moves.

```mermaid {alt="Recap chain: spot the access concern, write a class with the same interface, hold or create the real object, let callers keep calling the interface." caption="Look the same. Guard the way in."}
flowchart LR
  A["spot when / who / where"] --> B["same interface"] --> C["hold or create the real one"] --> D["callers can't tell"]
  class B c6
  class C c1
  class D good
```

Checklist:

- Is something besides the object's real job (loading, permission, location, logging) creeping into it?
- Does the stand-in implement exactly the same interface as the real object?
- Does it answer what it can itself and reach the real object only when it must?
- Are late failures and the moved delay acceptable to the caller?
- If it's lazy and shared, is the first creation thread-safe?

> **Look the same. Guard the way in.**

Related lessons: [Decorator](/patterns/decorator-pattern/), [Adapter](/patterns/adapter-pattern/),
[Facade](/patterns/facade-pattern/), [Singleton](/patterns/singleton-pattern/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Proxy.
- [`java.lang.reflect.Proxy`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/reflect/Proxy.html) javadoc.
- Hibernate ORM user guide: [Obtain an entity reference without initializing its data](https://docs.hibernate.org/orm/6.4/userguide/html_single/Hibernate_User_Guide.html).
