Virtual proxies

Defer creation of an expensive implementation until it is first used.

A virtual proxy stands in for an instance until something tries to use it. The first method call triggers the creation strategy, which builds the real implementation; subsequent calls go straight to the now-cached real instance.

When to use it

  • The real implementation is expensive to construct (loads a model, opens a connection, parses a file).
  • You want construction to happen lazily, in the calling thread, the first time the dependency is actually exercised.
  • You do not want to leak the laziness into the calling code — the caller receives the interface and uses it as if it were the real thing.

Builder usage

Service proxy = DynamicProxyBuilder
    .createVirtualProxy(Service.class, () -> new ExpensiveServiceImpl())
    .build();

The supplier is invoked at most once. The result is cached inside the proxy.

You can mix the virtual strategy with the other builder features. The factory only runs the first time a hook actually needs the instance.

Custom creation strategy

For finer control over caching, locking and reset semantics, supply a CreationStrategy directly through the strategy factory. The default strategy is single-instance, lazy, thread-safe.

Compile-time equivalent

For the same lazy behaviour without JDK dynamic proxies, see @StaticVirtualProxy.

Edit this page on GitHub ↗