Over a million developers have joined DZone.

Concise Embedded DSL Closures in Java

DZone's Guide to

Concise Embedded DSL Closures in Java

· ·
Free Resource

This trick was pointed to me (without the ThreadLocal part) by Rein Raudjärv, who saw it used in jMock.

The problem with Java “closures” aka anonymous inner classes being a tad too ugly is a well known one, but this semi-solution seems to be quite unused. Although you can apply the same principle for many situations it’ll work best for embedded DSLs.

Let’s start by defining an EDSL intefrace:

public interface DSL {
DSL doSomething();
DSL doSomethingElse();
DSLPreClosure closure();

As you can see we separated the actual closure application in a separate interface:

public interface DSLPreClosure {
DSL apply(DSLClosure closure);

The reason for that is that we want to use closures without defining a method in the anonymous inner class:

public class Test {
public static void main(String[] args) {
new DSLImpl()
.closure().apply(new DSLClosure() {{

What happens is that we abuse a little used Java feature — initializers. If you put a block in the body of a class definition it will be executed right after the constructor. In our case we construct a new subclass of DSLClosure and immediately add an initializer:

new DSLClosure() {
//Initializer starts here
//Closure body goes here
//Initializer ends here

Of course while this allows to execute a block of code with fewer symbols to write, we still need to somehow pass parameters. Note, that since the initializer executes inside the constructor call, it will be executed before the actual apply() method is called. Therefore we make use of the ThreadLocal class to pass the parameters inside the call:

public class DSLImpl implements DSLWithClosure {
static final ThreadLocal curDSL =
new ThreadLocal();
public DSL doSomething() {
//Do something…
return this;
public DSL doSomethingElse() {
//Do something else…
return this;
public DSLWithClosure closure() {
return this;
public DSL apply(DSLClosure closure) {
return this;

Finally the DSLClosure exposes the ThreadLocal parameter as a protected field:

public class DSLClosure {
protected DSL dsl =
(DSL) DSLImpl.curDSL.get();

Of course, for the sake of correctness we should also allow nesting closure calls on the same thread, so we should use a stack inside ThreadLocal, but this is left as an exercise to the reader :).

Jevgeni Kabanov is the Tech Lead of ZeroTurnaround, makers of JavaRebel. You can find more of his writing at the http://dow.ngra.de blog.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}