Closure in Java: fast and nice!

Working for two very important Banks, I have the need to play with Closure in Java. I have a lot of trouble looking at a good description of the subject, until I read a post on StackOverflow.

I have decided to re-cook this subject, adding a my specialized Example also.

Let’s start!

In Java anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or “delegates”. For example, take this interface:



You can use this anonymously to create a first-class function in Java. Let’s say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:


And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:


These methods are almost identical.
Using the first-class function type F, we can rewrite these into one method as follows:

You can use an anonymous class to use the firstMatch method:


For instance let’s implement a Generic Cache Decorator as a Closure.

Generic Cache Decorator with Java Closure

Scenario: We want to enable/disable a simple Cache Engine, keeping the code clean.
Is it possible to let a Client library to provide a Function, and then use a special CacheDecorator to delegate how to use it…
Let’s try:

The Decorator:


An example usage is:



public interface CacheFun<KeyToCache extends Serializable,TypeToCache extends Serializable>
* Funzione che implementa la business logic senza cache.
* Verrà chiamata solo se necessario
* @param key
* @return
* @throws Exception
public abstract TypeToCache f(KeyToCache key) throws Exception;

5 thoughts on “Closure in Java: fast and nice!”

  1. Pingback: Sysdent» Blog Archive » Project coin – Pequeñas mejoras para la plataforma java

Leave a Reply to Giovanni Giorgi Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.