Proxy

November 26, 20269 minutes

A 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.

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.

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. 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.
Two hundred loads before the screen appears.

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.

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). 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).
Same number, someone screening the calls.

The obvious version: the director answers his own phone

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

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.

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.

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:

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.

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. 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.
Only one line is about playing.

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.”

Class diagram: the Playlist uses the Track interface; both AudioTrack and LazyTrack implement Track; LazyTrack holds an AudioTrack, created on demand. Class diagram: the Playlist uses the Track interface; both AudioTrack and LazyTrack implement Track; LazyTrack holds an AudioTrack, created on demand.
Same interface outside; the real object behind it.

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.

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.

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.

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. 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.
Load once, on the first 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:

KindWhat it controlsIn this lesson
Virtual proxycreates the expensive object on demandLazyTrack
Protection proxychecks rights before passing a call onPremiumTrack
Remote proxystands in for an object that lives somewhere elsea song on a server
Smart referencea little housekeeping on every access: caching an answer, counting uses, logginga play counter

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

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:

Track track = new PremiumTrack(new LazyTrack(title, file), user);
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. 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.
The outer proxy stops the call before anything loads.

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:

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.)

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. 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.
No query until you touch the data.

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:

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 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: “Change the shape, not the job.”). An assistant who rewrites the director’s answers has stopped screening the calls. She’s editing them.

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. 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.
A decorator adds a job. A proxy decides who gets through.
InterfacePurpose
Proxysamecontrols access: when, whether, where
Decoratorsameadds a responsibility
Adapterdifferentmakes a class fit an interface you have
Facadenew, simplerone 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 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.

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. 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.
The delay moves. It doesn't vanish.

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.
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. 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.
Look the same. Guard the way in.

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, Adapter, Facade, Singleton.

Further reading