Core Java

Java Unleash Feature Flags Example

Feature flags, also known as feature toggles, are a powerful technique in software development that allows you to enable or disable features dynamically without deploying new code. This approach is beneficial for continuous delivery, A/B testing, and canary releases. Unleash is an open-source feature management tool that provides a platform for managing feature flags. In this article, we’ll explore the fundamentals of feature flags, how to configure them with Unleash, and how to integrate them into a Java application.

1. What is a Feature Flag?

A feature flag is a software development technique that allows developers to control whether certain features are enabled or disabled in a running application. This provides flexibility to:

  • Deploy new features safely without exposing them to all users.
  • Turn off faulty features instantly without redeploying.
  • Run A/B tests by enabling features for selected users.
  • Enable gradual rollouts instead of big-bang releases.

1.1 Benefits of Feature Flags

  • Safer Deployments
    • Deploy incomplete features without exposing them to users.
    • Reduce the risk of failed releases.
  • Instant Rollback
    • Disable problematic features immediately.
    • No need for hotfix deployments.
  • Controlled Rollouts
    • Gradually enable features for a percentage of users.
    • Test in production without impacting all users.
  • A/B Testing & Personalization
    • Show different features to different users.
    • Analyze performance before full rollout.
  • Better Continuous Delivery
    • Deploy frequently without worrying about incomplete features.
    • Reduce reliance on feature branches.

2. Introduction to Unleash

Unleash is an open-source feature flag management tool that provides a centralized way to manage feature toggles. It allows teams to enable, disable, or gradually roll out features using a simple dashboard.

2.1 Why Use Unleash?

  • Open-source & self-hosted – No vendor lock-in.
  • Flexible – Supports gradual rollouts, user targeting, and more.
  • Real-time updates – Features toggle without restarting the app.
  • Integration with multiple languages – Java, Python, Node.js, etc.

Unleash provides both a server-side API and a web dashboard to manage feature toggles easily.

3. Setting Up an Unleash Feature Flag Server

Before using Unleash in a Java application, we need to set up an Unleash server.

3.1 Running Unleash with Docker

Clone the Unleash repository using Git and build/run it with Docker. Open a terminal and execute the following commands:

1
2
3
git clone https://github.com/Unleash/unleash.git
cd unleash
docker compose up -d

Unleash is now installed on the machine and running in the background. This instance can be accessed in a web browser at http://localhost:4242.

3.2 Logging into the Unleash Dashboard

  • Open a browser and go to http://localhost:4242.
  • Log in with default credentials:
    • Username: admin
    • Password: unleash4all
Java Unleash Dashboard After Login
Unleash Dashboard After Login

3.3 Create a new feature flag

To create a flag, access the default project in the Unleash server, click “Create Flag“, enter a name (e.g., new-feature), and click “Create feature flag.”

Default Project - Unleash Server
Default Project – Unleash Server
Screenshot: Creating a Feature Toggle
Screenshot: Creating a Feature Toggle

The new feature flag has been created and is ready to use. Next, the flag should be enabled for the development environment to make it available in the Java application that will be cloned locally.

Enable Development strategy - Unleash Java Server

3.4 Generating an API Token

To integrate Unleash with a Java application, an API token is required. Next, generate an API token to authenticate calls to Unleash. This token will be used in our Java application’s configuration to toggle features securely. API tokens ensure only authorized applications can access feature flags and are managed by users with API access control.

In the left sidebar, expand the “Admin” section, select “API Access,” and click “New API Token.”

Enter a name for the token (e.g., java-app-token), select an environment (e.g., Development), choose the “Server-side SDK” token type, and click “Create Token.”

Screenshot – Creating an API Token
Screenshot – Creating an API Token

4. Adding Unleash to a Java Application

Now that Unleash is set up and running, the next step is to integrate it into a Java application. This integration allows the application to retrieve feature flag data from the Unleash server and dynamically enable or disable features based on the flag’s status. To achieve this, we need to add the necessary dependencies. For a Maven project, add the following dependency:

1
2
3
4
5
<dependency>
    <groupId>io.getunleash</groupId>
    <artifactId>unleash-client-java</artifactId>
    <version>9.2.6</version>
</dependency>

5. Configuring Unleash in Java

5.1 Connecting to the Unleash Server

Configure Unleash in a Java application for feature flag management.

01
02
03
04
05
06
07
08
09
10
11
12
13
public class UnleashConfig {
 
    public static Unleash setupUnleash() {
        io.getunleash.util.UnleashConfig config = io.getunleash.util.UnleashConfig.builder()
                .appName("my-java-app")
                .instanceId("instance-1")
                .unleashAPI("http://localhost:4242/api/")
                .apiKey("default:development.abc123") // Replace with actual API key
                .build();
 
        return new DefaultUnleash(config);
    }
}

The setupUnleash() method configures and initializes Unleash in our Java application, allowing it to interact with the Unleash server for feature flag management. Here’s a breakdown of each part:

The UnleashConfig.builder() method is used to build a configuration object that specifies how the Java application will connect to the Unleash server.

  • appName("my-java-app")
    • Sets the name of the application using Unleash.
    • This is useful for tracking which applications are making feature flag requests.
  • instanceId("instance-1")
    • Identifies the specific instance of the application.
    • Helps differentiate multiple instances of the same app when reporting usage.
  • unleashAPI("http://localhost:4242/api/")
    • Specifies the base URL of the Unleash server.
    • In this case, it points to a local Unleash instance running on port 4242.
  • apiKey("default:development.abc123")
    • Provides the API key required to authenticate requests to the Unleash server.
    • This ensures only authorized applications can fetch feature flag data.
    • The placeholder (default:development.abc123) should be replaced with the actual API key generated in the Unleash dashboard.
  • .build()
    • Constructs the UnleashConfig object with the specified settings.

The new DefaultUnleash(config) statement creates an instance of DefaultUnleash, which manages communication with the Unleash server and evaluates feature toggles. The method returns the initialized Unleash instance, allowing the application to check feature flags using Unleash’s API.

6. Using Feature Flags in Java

Now that Unleash is configured, we can check whether a feature is enabled before executing code.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
public class FeatureToggleService {
 
    private static final Logger logger = Logger.getLogger(FeatureToggleService.class.getName());
    private final Unleash unleash;
 
    public FeatureToggleService(Unleash unleash) {
        this.unleash = unleash;
    }
 
    public void executeFeature() throws InterruptedException {
        while (true) {
            Thread.sleep(2000);
            if (unleash.isEnabled("new-feature")) {
                logger.log(Level.INFO, "New feature is enabled!");
            } else {
                logger.log(Level.INFO, "New feature is disabled.");
            }
        }
    }
}

To test it:

1
2
3
4
5
6
7
8
9
public class UnleashFeatureToggle {
 
    public static void main(String[] args) throws InterruptedException {
        Unleash unleash = UnleashConfig.setupUnleash();
        FeatureToggleService service = new FeatureToggleService(unleash);
        service.executeFeature();
    }
       
}

If the new-feature toggle is enabled in Unleash, the message "New feature is enabled!" will be printed.

To deactivate the flag, disable the development option for the feature in the Unleash server. In Unleash, turn off new-feature in the development environment. After a few seconds, the application will update to reflect the latest flag status, resulting in the following output change in the terminal.

7. Conclusion

Implementing feature flags with Unleash in a Java application provides a powerful way to manage feature rollouts dynamically without modifying or redeploying code. By integrating Unleash, we can toggle features on or off, enable controlled rollouts, and safely test new functionalities in different environments. In this article, we covered the fundamentals of feature flags, set up Unleash, configured it with a Java application, and demonstrated how to enable and disable feature toggles in real time.

8. Download the Source Code

This article covered feature flags in Java using Unleash.

Download
You can download the full source code of this example here: java unleash feature flags

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest


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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button