Proxy: lazy loading and access control
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite listing page shows 40 products, and loading every 4 MB image makes it crawl. Anyone can also call changePrice. How do you control when and by whom an object is used?
Proxy: a stand-in that controls access
A proxy is a stand-in object with the same interface as the real object. It decides when, whether and how the real object is used.
A proxy implements the same interface as the real subject and holds or creates it. Below, LazyImageProxy creates the real image only when show() is first called.
interface ProductImage { void show(); }
class LazyImageProxy implements ProductImage { // same interface as the real image private final String sku; private HighResImage real; // the real subject, created later
LazyImageProxy(String sku) { this.sku = sku; }
public void show() { if (real == null) real = new HighResImage(sku); // control: create on first use real.show(); // then forward }}Each proxy method can check something, delay something or reuse an earlier answer before it forwards the call, and it may decide not to forward at all. Think of a college fest pass desk: visitors deal with the desk, not the auditorium, and the desk can check passes or answer "house full" without opening the door.
The common kinds of proxy:
- Virtual proxy: creates an expensive object only when it is first needed.
- Protection proxy: checks who is calling before letting the call through.
- Caching proxy: remembers answers and skips repeated slow calls.
- Remote proxy: looks local but sends the call over the network (an HTTP client stub).
Virtual proxy: load the heavy image only when shown
A virtual proxy stands in for an object that is expensive to create and builds the real object only on first use. This is called lazy loading.
A virtual proxy stands in for something expensive, such as a 4 MB product image. Example 1 builds three cheap proxies and loads only the image the shopper opens.
Example 1 · Virtual proxy: images load on first show
import java.util.List;
interface ProductImage { void show();}
class HighResImage implements ProductImage { private final String sku;
HighResImage(String sku) { this.sku = sku; System.out.println(" loading 4 MB image for " + sku); // the expensive part }
@Override public void show() { System.out.println(" showing image of " + sku); }}
class LazyImageProxy implements ProductImage { private final String sku; private HighResImage real; // null until first needed
LazyImageProxy(String sku) { this.sku = sku; }
@Override public void show() { if (real == null) { real = new HighResImage(sku); } real.show(); }}
public class VirtualProxyDemo { public static void main(String[] args) { List<ProductImage> page = List.of( new LazyImageProxy("PEN-01"), new LazyImageProxy("BAG-07"), new LazyImageProxy("MUG-03")); System.out.println("Listing page ready with " + page.size() + " images");
System.out.println("Shopper opens BAG-07:"); page.get(1).show(); System.out.println("Shopper opens BAG-07 again:"); page.get(1).show(); }}Listing page ready with 3 images Shopper opens BAG-07: loading 4 MB image for BAG-07 showing image of BAG-07 Shopper opens BAG-07 again: showing image of BAG-07
What this code does
- Building the page created three cheap proxies and loaded nothing. Only the image the shopper opened was loaded, and only once.
- The page's list has the type
List<ProductImage>, so the code that callsshow()cannot tell a proxy from a real image.
The proxy is cheap: it keeps only the SKU, creates the real image the first time show() is called and reuses it after that. A listing page may build 40 product cards while the shopper opens two, so only two images are loaded.
This idea is called lazy loading; JPA uses the same trick for related entities you have not touched yet.
Protection proxy: only admins can change prices
A protection proxy checks permission before forwarding a call, so the real object needs no role checks of its own.
SecuredPriceService lets everyone read prices, but changePrice throws a SecurityException unless the current user is an admin. Example 2 tries it as an admin and as a customer.
Example 2 · Protection proxy: SecuredPriceService
import java.util.HashMap;import java.util.List;import java.util.Map;
record User(String name, String role) {}
interface PriceService { int priceOf(String sku); void changePrice(String sku, int rupees);}
class SimplePriceService implements PriceService { private final Map<String, Integer> prices = new HashMap<>(Map.of("PEN-01", 20, "BAG-07", 899));
public int priceOf(String sku) { return prices.get(sku); }
public void changePrice(String sku, int rupees) { prices.put(sku, rupees); System.out.println(" price of " + sku + " is now Rs " + rupees); }}
class SecuredPriceService implements PriceService { private final PriceService real; private final User user;
SecuredPriceService(PriceService real, User user) { this.real = real; this.user = user; }
public int priceOf(String sku) { return real.priceOf(sku); // everyone may read }
public void changePrice(String sku, int rupees) { if (!user.role().equals("ADMIN")) { // only admins may write throw new SecurityException(user.name() + " may not change prices"); } real.changePrice(sku, rupees); }}
public class ProtectionProxyDemo { public static void main(String[] args) { PriceService store = new SimplePriceService(); for (User user : List.of(new User("Asha", "ADMIN"), new User("Ravi", "CUSTOMER"))) { PriceService prices = new SecuredPriceService(store, user); System.out.println(user.name() + " sees BAG-07 at Rs " + prices.priceOf("BAG-07")); try { prices.changePrice("BAG-07", 799); } catch (SecurityException e) { System.out.println(" blocked: " + e.getMessage()); } } }}Asha sees BAG-07 at Rs 899 price of BAG-07 is now Rs 799 Ravi sees BAG-07 at Rs 799 blocked: Ravi may not change prices
What this code does
- Both users read the price through the proxy. Only Asha's
changePricereaches the real service; Ravi's call stops at the check and never touches the price map. - Ravi sees Rs 799 because Asha's change went into the shared real service. The proxy controls who may write; it does not keep its own copy.
The real PriceService stays simple and contains no role checks. Security lives in one place, and the code that uses the service cannot forget it, because it only ever receives the proxy.
Predict the output
Who gets through?
The proxy allows reads for everyone and price changes for ADMIN only. Ravi is a CUSTOMER.
Round 1 of 2
Ravi reads a price.
Caching proxy for repeated product lookups
A caching proxy keeps answers in a map: on a hit it returns the stored answer, on a miss it asks the real object and stores the result.
A caching proxy remembers answers so repeated lookups skip the database. Example 3 looks up five SKUs and counts the real queries, and Example 4 shows the stale-data trap.
Example 3 · Caching proxy: hits and misses
import java.util.HashMap;import java.util.List;import java.util.Map;record Product(String sku, String name, int price) {}
interface ProductRepository { Product findBySku(String sku);}
class DatabaseProductRepository implements ProductRepository { private final Map<String, Product> table = new HashMap<>();
DatabaseProductRepository() { table.put("PEN-01", new Product("PEN-01", "Gel pen", 20)); table.put("BAG-07", new Product("BAG-07", "Laptop bag", 899)); }
public Product findBySku(String sku) { System.out.println(" DB query: " + sku); // pretend this is slow return table.get(sku); }}
class CachingProductRepository implements ProductRepository { private final ProductRepository real; private final Map<String, Product> cache = new HashMap<>(); private int hits; private int misses;
CachingProductRepository(ProductRepository real) { this.real = real; }
public Product findBySku(String sku) { Product cached = cache.get(sku); if (cached != null) { hits++; return cached; // no call to the real object } misses++; Product fresh = real.findBySku(sku); if (fresh != null) { cache.put(sku, fresh); } return fresh; }
String stats() { return "hits " + hits + ", misses " + misses; }}
public class CachingProxyDemo { public static void main(String[] args) { CachingProductRepository repo = new CachingProductRepository(new DatabaseProductRepository()); for (String sku : List.of("PEN-01", "BAG-07", "PEN-01", "PEN-01", "BAG-07")) { System.out.println(sku + " -> " + repo.findBySku(sku).name()); } System.out.println("Cache: " + repo.stats()); }}DB query: PEN-01 PEN-01 -> Gel pen DB query: BAG-07 BAG-07 -> Laptop bag PEN-01 -> Gel pen PEN-01 -> Gel pen BAG-07 -> Laptop bag Cache: hits 3, misses 2
What this code does
- Five lookups made only two database queries: the first lookup of each SKU is a miss, every later one is a hit.
- Missing SKUs (
null) are not stored, so a product added later is still found.cache.computeIfAbsent(sku, real::findBySku)is a shorter way to write the same logic.
Example 4 · The stale cache trap, and evicting an entry
import java.util.HashMap;import java.util.Map;record Product(String sku, String name, int price) {}
interface ProductRepository { Product findBySku(String sku);}
class DatabaseProductRepository implements ProductRepository { private final Map<String, Product> table = new HashMap<>();
DatabaseProductRepository() { table.put("PEN-01", new Product("PEN-01", "Gel pen", 20)); }
public Product findBySku(String sku) { System.out.println(" DB query: " + sku); return table.get(sku); }
void updatePrice(String sku, int rupees) { Product old = table.get(sku); table.put(sku, new Product(sku, old.name(), rupees)); }}
class CachingProductRepository implements ProductRepository { private final ProductRepository real; private final Map<String, Product> cache = new HashMap<>();
CachingProductRepository(ProductRepository real) { this.real = real; }
public Product findBySku(String sku) { return cache.computeIfAbsent(sku, real::findBySku); }
void evict(String sku) { cache.remove(sku); }}
public class StaleCacheDemo { public static void main(String[] args) { DatabaseProductRepository db = new DatabaseProductRepository(); CachingProductRepository repo = new CachingProductRepository(db);
System.out.println("Price: Rs " + repo.findBySku("PEN-01").price()); db.updatePrice("PEN-01", 25); System.out.println("After DB update: Rs " + repo.findBySku("PEN-01").price()); repo.evict("PEN-01"); System.out.println("After evict: Rs " + repo.findBySku("PEN-01").price()); }}DB query: PEN-01 Price: Rs 20 After DB update: Rs 20 DB query: PEN-01 After evict: Rs 25
What this code does
- The database changed the pen to Rs 25, but the proxy answered from its map and still said Rs 20. This is stale data.
evictremoves the entry, so the next lookup is a miss that reads the new price. Real code evicts inside the update path, so nobody can forget.
A hit means the answer is already stored; a miss means the proxy asks the real object and stores the answer. Product pages ask for the same popular products again and again, so most lookups never reach the database.
The cost is stale data: if the price changes in the database, the cache still holds the old one. A caching proxy needs a rule for removing entries, called eviction: after an update, after some minutes, or when the cache is full.
Find the bug
Find the caching bug
Each version of the caching proxy has one wrong line. Click it.
Every lookup still queries the database.
Round 1 of 2HashMap cache is fine for one thread. Code shared by many threads needs ConcurrentHashMap or a cache library.Proxy vs decorator: same shape, different intent
Example 5 puts a logging decorator around a caching proxy. Both wrappers have the same shape, so the question is why each one exists.
Example 5 · A decorator around a proxy: who decides what
import java.util.HashMap;import java.util.Map;record Product(String sku, String name, int price) {}
interface ProductRepository { Product findBySku(String sku);}
class DatabaseProductRepository implements ProductRepository { public Product findBySku(String sku) { System.out.println(" DB query: " + sku); return new Product(sku, "Gel pen", 20); }}
class CachingProductRepository implements ProductRepository { // proxy: controls access private final ProductRepository real; private final Map<String, Product> cache = new HashMap<>();
CachingProductRepository(ProductRepository real) { this.real = real; }
public Product findBySku(String sku) { return cache.computeIfAbsent(sku, real::findBySku); // may skip the real call }}
class LoggingRepository implements ProductRepository { // decorator: adds behaviour private final ProductRepository inner;
LoggingRepository(ProductRepository inner) { this.inner = inner; }
public Product findBySku(String sku) { System.out.println("[log] find " + sku); return inner.findBySku(sku); }}
public class ProxyVsDecoratorDemo { static ProductRepository productRepository() { return new CachingProductRepository(new DatabaseProductRepository()); }
public static void main(String[] args) { ProductRepository repo = new LoggingRepository(productRepository()); repo.findBySku("PEN-01"); repo.findBySku("PEN-01"); }}[log] find PEN-01 DB query: PEN-01 [log] find PEN-01
What this code does
- Both wrappers have the same shape. The logging decorator always forwards and was added by the caller on purpose; the caching proxy sits behind
productRepository(), the caller never sees it, and it skips the database on the second call. - Each wrapper has one job, so they combine cleanly: two log lines, one database query.
In code, a proxy and a decorator look the same: both implement the interface and hold another object of it. The difference is the intent. A decorator always forwards and adds behaviour, and the caller usually stacks decorators on purpose. A proxy controls access: it may create the real object, block the call or answer from a cache, and the caller usually does not know it is there.
Ask "why does this wrapper exist?" If the answer is "to add something", it is a decorator. If it is "to guard or manage the real object", it is a proxy.
Next step
Check your understanding
12 quick questions