Posts Tagged: java


16
Jun 08

Ultralightweight

EJB 3.x are ultralightweight — OMG! What’s next? Weightless? Antigravity frameworks? And I thought “Plain Old Java Object” was funny :)


10
Jun 08

Yet Another Java Trick, Revisited

Interestingly enough I rewrote by now both places in code that I did according to the Yet Another Java Trick. It’s a neat trick, which may come back to me in some other context, but it definitely isn’t as useful as I thought for logging result.


20
May 08

The JSR 292 — invokedynamic

I read through the first draft of JSR 292 this morning and had several questions that I’m not 100% sure the current specification addresses:

  • Can I rebind the CallSite after I have set the MethodHandle?
  • Can I keep a reference to CallSites at all?
  • Is the setMethodHanlde method implied to be thread-safe?

The reason I’m asking is that the only way to rebind a method as seen in spec is lazily, by invalidating all the call sites in the class (or everywhere) and rebinding methods when called. It may sometimes be necessary or easier to do that eagerly and it looks like the current API does allow that. It should either be forbidden explicitly or allowed explicitly.

I’ll send a link to the JSR-292-COMMENTS list as well, but perhaps someone knows the answer already?


19
May 08

Concise EDSL Closures in Java

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:
[java]
public interface DSL {

DSL doSomething();
DSL doSomethingElse();
DSLPreClosure closure();
}
[/java]

As you can see we separated the actual closure application in a separate interface:
[java]
public interface DSLPreClosure {
DSL apply(DSLClosure closure);
}
[/java]

The reason for that is that we want to use closures without defining a method in the anonymous inner class:
[java]
public class Test {
public static void main(String[] args) {
new DSLImpl()
.doSomething()
.closure().apply(new DSLClosure() {{
dsl
.doSomething()
.doSomethingElse();
}})
.doSomethingElse();
}
}
[/java]

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:
[java]
new DSLClosure() {
//Initializer starts here
{
//Closure body goes here
}
//Initializer ends here
};
[/java]

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:
[java]
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() {
curDSL.set(this);
return this;
}

public DSL apply(DSLClosure closure) {
curDSL.set(null);
return this;
}
}
[/java]

Finally the DSLClosure exposes the ThreadLocal parameter as a protected field:
[java]
public class DSLClosure {
protected DSL dsl =
(DSL) DSLImpl.curDSL.get();
}
[/java]

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 :)


26
Apr 08

An embedded Java DSL for manipulating hierarchical JavaBeans

Just yesterday I was thinking on how to improve the DSLs I’m working on at the moment and got an idea, which wasn’t too useful in the context of SQL, but could be used for something else.

Imagine we have three JavaBeans (I’m omitting getters/setters for readability):
[java]
class Company {
String name;
Address address;
Collection employees;
}

class Address {
String country;
String zip;
String town;
String street;
}

class Employee {
String firstName;
String lastName;
Address address;
}
[/java]

It’s a straightforward task to build a DSL for manipulating this data. It could look something like that:
[java]
Company c = new CompanyBuilder()
.name(“ZeroTurnaround”)
.address()
.country(“Estonia”)
.finish()
.addEmployee()
.firstName(“Jevgeni”)
.lastName(“Kabanov”)
.address()
.country(“Estonia”)
.finish()
.finish()
.toCompany();
[/java]

The trick is that the AddressBuilder hiding behind the address() call is used in two contexts — as an employee address and as a company address. In a large domain such situations are very common and we would like the corresponding builders to be reused.

What we can do is make every builder keep in mind it’s parent context like this:
[java]
public class EmployeeBuilder
implements Builder {
PARENT parent;

public EmployeeBuilder(Employee e, PARENT parent) {
this.parent = parent;
}

//Field setters …

public AddressBuilder>
addAddress() {
return
new AddressBuilder>(this);
}

public PARENT finish() {
return parent;
}
}

public class AddressBuilder
implements Builder {
PARENT parent;

public AddressBuilder(Address a, PARENT parent) {
this.parent = parent;
}

//Field setters …

public PARENT finish() {
return parent;
}
}
[/java]

This way the generic type becomes nested and holds the whole path to the root of the hierarchy in a typesafe way. Of course we also need to return the actual value independently of the parent, but it’s easy to do by passing a corresponding closure from the parent and calling it in the finish:

[java]

public class AddressBuilder
implements Builder {
//…

interface Closure {
void address(Address address);
}

public PARENT finish() {
addressClosure.address(address);
return parent;
}
}
[/java]

This trick can be reused for any kind of hierarchical composition — JavaBeans, XML and so on. For XML you could generate the DSL from the Schema, which is a relatively painful process. However for JavaBeans you can generate a builder per bean in a very straightforward way from the reflection information. Such a builder could be used for modifying JavaBeans as well as for constructing them.

It would most probably be simplest to output the bytecode directly and generate .class files or JAR for this DSL, which makes it an ideal test case for the typesafe bytecode engineering DSL library I’m working on :) Most likely I’ll implement this language as an example of using typesafe bytecode engineering, so if you’re interested keep an eye on the blog.