Search This Blog

Posts

Not too often but sometimes we are forced to write custom dynamic proxy class using java.lang.reflect.Proxy. There is really no magic in this mechanism and it's worth knowing even you will never really use it - because Java proxies are ubiquitous in various frameworks and libraries.

The idea is quite simple: dynamically create an object that implements one or more interfaces but every time any method of these interfaces is called our custom callback handler is invoked. This handler receives a handle to a method that was called (java.lang.reflect.Method instance) and is free to behave in any way. Proxies are often used to implement seamless mocking, caching, transactions, security - i.e. they are a foundation for AOP.

Before I explain what the purpose of com.google.common.reflect.AbstractInvocationHandler from the title, let's start from a simple example. Say we want to transparently run methods of given interface asynchronously in a thread pool. Popular stacks like Spring (se…

During my talk at Warsaw Java Users Group about functional reactive programming in Java a few interesting questions came up regarding CompletableFuture capabilities. One person was interested whether it's possible to wait for the first completed future that is passing a given predicate rather than just the first one (like CompletableFuture.anyOf()). This is similar requirement to Future.find() in Scala. It's not built into CompletableFuture but quite easy to implement using the concept of promises.

Our custom implementation will take two parameters: a list of homogeneous futures and a predicate. The first future to complete that matches given predicate wins. If no future matched resulting future never ends (rather easy to change that behaviour). We will use a thread-safe and lightweight AtomicBoolean completed flag because callbacks will be invoked from multiple threads.