For everyone — The house's electrical panel

In a well-built house, no room powers the others: all connections go through an electrical panel, where each switch is wired to its lamp, each outlet to its circuit. Changing a lamp? You plug a different connector into the panel, without touching the walls. Google Guice played the role of that panel in the project's Java programs: a lightweight container that connects each component to what it needs, without the components having to know one another.

Why should you care? Because centralized wiring is what lets a house be reorganized without being demolished. In the Yokul project, the building blocks of the virtual world — perception, decision-making, behaviors — were wired together by Guice for years (until 2017); they were then re-plugged, with no rewrite, onto the CDI standard (Jakarta) that came with Apache Quarkus. Two wiring engines, the same house: the story had a happy ending — and that is not an ending you always get in large projects.

The principle behind this panel is covered in detail in the companion article Inversion of Control; here, the focus is on the tool.

The full text

Guice in brief

Google Guice is an open source dependency injection framework developed by Google — the bulk of the credit goes to Bob Lee, with Kevin Bourrillion at his side. It applies the IoC pattern in Java with a lightweight approach:

  • annotations (@Inject, @Singleton...) to mark the classes and constructors managed by the container;
  • module-based configuration, i.e. dedicated classes that declare the bindings between interfaces and implementations;
  • programmatic configuration also possible, via the Java API, when modules are not enough.

The spirit of the tool is right there in its name, in fact: "juice" — what circulates between the components. An injected energy, not a do-everything machine.

A simple example

Suppose a class ServiceA depends on an instance of ServiceB. A Guice module declares the dependency configuration:

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(ServiceB.class).toInstance(new ServiceB());
        bind(ServiceA.class);
    }
}

Then the application creates the container and asks it for an instance:

public class MyApp {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new MyModule());
        ServiceA serviceA = injector.getInstance(ServiceA.class);
        serviceA.doSomething();
    }
}

Guice automatically resolves all the dependencies of ServiceA from the configuration defined in the module: nowhere does the application code instantiate ServiceB itself.

The three types of dependency injection

See the details of the three styles (constructor, method, field) in the article Inversion of Control — the same code works with Guice: you only need to add @Inject. The container adds to the pattern nothing more than its machinery: modules, scopes, minutes of centralized wiring.

Scopes

A scope defines the lifetime of an instance managed by Guice: a single instance shared across the whole application (singleton), one instance per request or per session in a web application, or any other rule defined by the application. Guice ships the usual predefined scopes — singleton, request, session — and lets you define custom ones.

For example, a scope tied to the current thread:

public class MyScope implements Scope {
    private final ThreadLocal<Object> values = new ThreadLocal<>();

    @Override
    public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
        return () -> {
            T current = (T) values.get();
            if (current == null) {
                current = unscoped.get();
                values.set(current);
            }
            return current;
        };
    }
}

For the simulation, this point mattered: a virtual world keeps thousands of objects alive whose lifetimes are nothing alike — an actor lives for simulated years, a perception for the duration of a single time step — and scopes offer a single place to express those rules.

The event bus

Guice also provides a publish/subscribe mechanism for events, the event bus. A listener declares the types of events it handles, registers with the bus, and receives the published events:

public class MyListener {
    @Subscribe
    public void handleEvent(MyEvent event) {
        // Gérer l'événement ici
    }
}
public class MyApp {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new MyModule());
        EventBus eventBus = injector.getInstance(EventBus.class);
        MyListener listener = new MyListener();
        eventBus.register(listener);
        eventBus.post(new MyEvent());
    }
}

Here, MyListener handles events of type MyEvent; it is registered with the event bus — itself instantiated by Guice — and the event is published via the post method. It is at the very least a cousin of what would later become the project's message queues (see Message queues): circulating events without senders and receivers knowing each other — the local, lightweight version.

Advantages and limitations

The strengths: configuration is separated from business logic, the injection syntax is simple and reduces coupling between components, instance lifetimes are handled efficiently — which matters for large applications — and the whole thing is extensible and integrates naturally with tools like JUnit or Hibernate.

The limitations: the concept requires a learning curve for anyone who has never practiced IoC; for a small application, the machinery can cost more than it delivers; and some situations remain tricky — instances created dynamically at runtime, or shared across several threads. That last limitation in particular weighed on the simulation: a world that creates its actors on the fly and at high speed stresses the fragile corners of the container.

2017: the end of the Guice adventure

The project's story with Guice ends in 2017: the container stayed in place until that date, and then the project waited for a transition — one that would arrive a few years later, with the arrival of Apache Quarkus. It provides the whole of the machinery that allowed Guice (and, along the way, Apache Camel) to exist, including dependency injection via CDI — the injection standard of the Jakarta EE ecosystem (the enterprise edition of Java, formerly J2EE) — with a more efficient implementation and one natively geared toward modern deployment.

The replacement only required rewriting the bindings: the components themselves did not move — that was already the promise of IoC. A container that can be dismantled cleanly is the best proof that it did its job well; and Guice served the project faithfully for a decade all the same.

For Yokul

This is exactly the role Guice played in the project: the assembler of the open source building blocks of the virtual world — a single composition engine for perception, decision-making, behaviors — without those blocks knowing one another. Since then, Apache Quarkus has provided the same capability via CDI, more efficiently; but the principle stands: assemble, don't couple.

See also