← Blog

Feature flags in Java without a vendor SDK

A feature flag in Java is a runtime check that turns a code path on or off without a new deploy, the same mechanism as in any other language. You do not need LaunchDarkly’s Java SDK or Split’s Java SDK to get one working. Store the flag as a file, hash the user id yourself, and check the result at the call site.

Most Java shops already have a PR review workflow for everything else in the repo. Adding a vendor SDK means a new dependency in pom.xml or build.gradle, a background thread that polls or streams updates, and a flag whose state lives in a dashboard disconnected from the code that reads it. dif’s own CLI and compiled client are JavaScript and TypeScript only, so there is no @dif.sh/sdk for Java to install. What follows is a hand-rolled port of the same model, deterministic bucketing and a flag that is a file in your repo, built with nothing beyond the JDK.

Key Takeaways

  • A feature flag in Java needs no vendor SDK: a file in your repo plus about twenty lines of SHA-256 hashing gives you deterministic, local assignment.
  • dif’s bucketing formula, SHA-256(salt || user_id) mod 10,000, ports directly to Java’s MessageDigest, with no network call to evaluate a flag.
  • dif’s CLI and compiled client are JavaScript and TypeScript only. This guide hand-rolls the same git-native model in Java rather than installing an SDK that does not exist yet.
  • Validate flags in a JUnit test instead of a CI plugin: check that weights sum to 100 and every flag has an owner before the build passes.
  • The tradeoff: you give up dif build’s typed client and orphan detection, so a renamed flag id fails at runtime, not at compile time, unless you write that check yourself.

Why Java teams skip the vendor SDK

LaunchDarkly’s Java SDK opens a streaming connection so flag changes reach a running JVM in under a second. That is a real advantage for an instant kill switch on a payment path. The cost is a dependency most Java services do not otherwise need, a connection to keep alive, and a flag whose true state lives in a web dashboard rather than the git history the rest of the codebase already has.

For a flag that does not need a sub-second remote kill, for example a staged rollout you are ramping over a sprint, the dashboard and the streaming client buy you nothing over a Markdown file reviewed in a pull request. The rollback is editing a number and merging, and the reason is in the commit log instead of someone’s memory of a dashboard toggle. The thesis behind feature flags in your repo holds regardless of language: a flag is part of the codebase, so it belongs in the codebase.

The flag as one file, not a dashboard row

A flag is YAML frontmatter on top of a short explanation, checked into the repo next to the code it gates:

---
id: new-checkout
owner: priya@acme.dev
surface: checkout
variants:
  - name: off
    weight: 50
  - name: on
    weight: 50
---

Ramping the new checkout flow. Kill switch for the payment regression from Q3.

This is the same shape dif uses for its own .md flags: an owner, a surface, and a list of variants with weights that sum to 100. The flag file format documents the full schema if you want to match it exactly. Ramping the rollout means editing weight from 50 to 90 and opening a PR, not logging into anything.

Port the bucketing math to Java

dif assigns a variant by hashing the user id with the flag’s salt and taking the first four bytes of the digest, read as a big-endian integer, modulo 10,000. The same math runs in Rust and TypeScript today; porting it to Java is a direct translation with MessageDigest:

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class FlagBucket {
    private FlagBucket() {}

    public static int bucket(String salt, String userId) {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            sha256.update(salt.getBytes(StandardCharsets.UTF_8));
            byte[] hash = sha256.digest(userId.getBytes(StandardCharsets.UTF_8));
            int firstFourBytes = ((hash[0] & 0xFF) << 24)
                | ((hash[1] & 0xFF) << 16)
                | ((hash[2] & 0xFF) << 8)
                | (hash[3] & 0xFF);
            return Math.floorMod(firstFourBytes, 10_000);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-256 not available", e);
        }
    }
}

SHA-256 is specified in NIST FIPS 180-4, so this is the same standard hash every language implementation uses. Nothing here calls out to a network, and MessageDigest ships in the JDK, so the method has no dependency beyond java.security.

Pick a variant from cumulative weights

Think of each flag as 10,000 numbered seats, painted by weight. A 50/50 flag paints seats 0-4,999 off and 5,000-9,999 on. Walking the variant list and accumulating weight gives you the seat boundaries:

public record Variant(String name, int weightPercent) {}

public static String assign(int bucket, List<Variant> variants) {
    int cumulativeBuckets = 0;
    for (Variant v : variants) {
        cumulativeBuckets += v.weightPercent() * 100;
        if (bucket < cumulativeBuckets) {
            return v.name();
        }
    }
    throw new IllegalStateException("variant weights do not sum to 100");
}

Because the bucket is a pure function of the salt and the user id, the same user always lands in the same seat. Widening a rollout from 10% to 50% only repaints more seats on; nobody who already has the feature loses it mid-rollout.

Check the flag at the call site

Load the flag files once at startup with a generic YAML parser like SnakeYAML, build a map keyed by id, and expose one method that combines the bucket and the assignment:

public class FlagRegistry {
    private final Map<String, FlagDefinition> flags;

    public FlagRegistry(Map<String, FlagDefinition> flags) {
        this.flags = flags;
    }

    public String variant(String flagId, String userId) {
        FlagDefinition flag = flags.get(flagId);
        if (flag == null) {
            return "off";
        }
        int bucket = FlagBucket.bucket(flagId, userId);
        return FlagBucket.assign(bucket, flag.variants());
    }
}

The call site reads like any other conditional. There is no client to initialize and no request in flight while it evaluates:

if (flags.variant("new-checkout", userId).equals("on")) {
    return newCheckout(request);
}
return legacyCheckout(request);

An unknown flag id resolves to off and does nothing else, the same fail-safe behavior dif’s own SDK guarantees: a misconfigured flag means nobody sees the new thing, not an incident.

Validate flags before the build, not after an incident

dif validate checks weight totals, owner format, and flag references in one pass for a JS/TS repo. A Java codebase with no CLI to install gets the same guarantee from a JUnit test that walks the flag directory:

@Test
void everyFlagHasAnOwnerAndValidWeights() throws IOException {
    for (Path flagFile : flagFiles()) {
        FlagDefinition flag = parseFrontmatter(flagFile);
        assertTrue(flag.owner().contains("@"), flagFile + " has no owner email");
        int total = flag.variants().stream().mapToInt(Variant::weightPercent).sum();
        assertEquals(100, total, flagFile + " weights do not sum to 100");
    }
}

That test fails the build the same way a broken compile does, so a bad flag never reaches a PR review. It is a thinner check than dif validate runs, catching weight and owner mistakes but not orphan call sites or cross-flag collisions, because nothing in this setup scans your Java source for flags.variant("...") references.

What you give up without the SDK

Three things dif’s compiled client gives a JS/TS project do not come free in this Java port. There is no typed client, so a renamed flag id is a runtime miss, not a compile error. There is no orphan scan, so a flag deleted from dif/flags/ but still referenced in a controller fails silently rather than failing dif validate. And there is no context.json, so a coding agent working in this Java repo has no single file summarizing what is live.

For a team that wants the full workflow, collision detection, orphan detection, and the agent-readable summary, that tooling exists today for JavaScript and TypeScript. For a Java backend, the git-native model (the file, the deterministic hash, the PR review) ports cleanly. The validation and compile-time safety dif’s CLI adds for its own supported languages does not, unless you build it yourself.

FAQ

Is there a dif SDK for Java? No. dif’s SDK is JavaScript and TypeScript today, with adapters for React and Svelte. The bucketing algorithm is portable, and the code above is a hand-rolled Java port of the same math, not an installed package.

How do I add feature flags to a Java app without LaunchDarkly? Store each flag as a file in your repo, hash the user id into a bucket with SHA-256 modulo 10,000, and check the result at the call site. No vendor SDK, dashboard, or network call is required.

How do feature flags avoid a network call in Java? Assignment is a pure function of the salt and the user id, computed locally with MessageDigest. Nothing is stored or fetched over the network, so evaluating a flag costs one hash, not one request.

Can I validate feature flags in CI without a vendor SDK? Yes. A JUnit test that parses each flag file and asserts the weights sum to 100 and the owner field is a valid email catches the same mistakes dif validate catches for a JS/TS CLI.

What is the difference between a feature flag and a feature toggle in Java? None. They are two names for the same mechanism, per Martin Fowler’s feature toggles article: wrap a code path in a condition and decide at runtime whether it runs.

Getting it running

A feature flag in Java comes down to a file, a hash, and a conditional. Store the flag as Markdown with frontmatter next to the code it gates, port the SHA-256 mod 10,000 bucketing into a small utility class, and check the variant at the call site with no client to initialize. A JUnit test replaces dif validate for the weight and owner checks a CI plugin would otherwise run.

If your stack is JavaScript or TypeScript instead, this workflow already ships: npm install -g @dif.sh/cli, then dif init gives you the CLI, the compiled client, and the agent-readable context in about two minutes.

For Java, start from the flag file format reference and feature flags in git for the full case on keeping flags in the repo, then port the hashing function above into your own codebase.